使用python提取完整的XML块

时间:2018-11-28 04:57:48

标签: python xml linux elementtree

是否可以使用Python从XML文件中提取完整的XML文本块?我将Python与ElementTree结合使用,以从XML提取标签和值,以便比较2个XML文件。 但是是否可以提取XML块的整个文本?

例如:

<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>

是否可以使用python(ElementTree)从上述XML中提取一个特定的完整块(),如下所示?

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

2 个答案:

答案 0 :(得分:2)

使用etree解析文档后,您可以做几件事

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

将元素作为字符串获取只是

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

EDIT 注意,比较元素不一定是最好的方法。 另请参见here

答案 1 :(得分:0)

发现lxml是在两个XML标签之间提取完整文本的最佳选择。

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>