3
votes

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
you want to parse an xml document, get a fragment and turn that fragment back to a string? - richflow
Yup. I need the complete contents of a block to compare it with similar content in another file - Timothy Henry

2 Answers

6
votes

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
votes

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>