3

Is it possible to extract complete blocks of XML text from an XML file using Python? I am using ElementTree with Python to extract tags and values from XML, in order to compare 2 XML files. But is it possible to extract the whole text of an XML block?

For example:

<stats>
<player>
    <name>Luca Toni</name>
    <matches>47</matches>
    <goals>16</goals>
    <WC>yes</WC>
</player>
<player>
    <name>Alberto Gilardino</name>
    <matches>57</matches>
    <goals>19</goals>
    <WC>yes</WC>
</player>
<player>
    <name>Mario Balotelli</name>
            <matches>36</matches>
            <goals>14</goals>
            <WC>yes</WC>
</player>
</stats>

Is it possible to extract one particular complete block (), as given below, from the above XML using python (ElementTree)?

<player>
    <name>Luca Toni</name>
    <matches>47</matches>
    <goals>16</goals>
    <WC>yes</WC>
</player>
2
  • 1
    you want to parse an xml document, get a fragment and turn that fragment back to a string?
    – richflow
    Nov 28, 2018 at 5:04
  • Yup. I need the complete contents of a block to compare it with similar content in another file Nov 29, 2018 at 1:20

2 Answers 2

6

Once you've parsed your document with etree, you can do several things

import xml.etree.ElementTree  as ET

doc = ET.parse('test.xml')
root = doc.getroot()

print(root.find("player"))                  # get first player
print(root.find(".//player"))               # get first player if it's not a direct child
print([p for p in root.findall("player")])  # get all players (direct children)
print([p for p in root.getchildren()])      # get direct children

getting an element as a string is just

test = ET.tostring(root.find("player"))
print(text)

EDIT note that to compare elements, this is not necessarily the best method. See here for another option.

-1

Found that lxml was the best option to extract complete text between two XML tags.

from lxml import etree
node1=etree.parse("azzurri.xml")
e1=node1.xpath(".//player")IndentationError: unexpected indent
for ele1 in e1:
    pl=ele1.xpath(".//name")
    for pl1 in pl:
         if pl1.text=="Luca Toni":
                rl1=ele1.text + ''.join(map(etree.tostring, ele1)).strip()
                print rl1


<name>Luca Toni</name>
<matches>47</matches>
<goals>16</goals>
<WC>yes</WC>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.