使用python提取完整的XML块

2024-09-21 01:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用Python从XML文件中提取完整的XML文本块?我使用ElementTree和Python从XML中提取标记和值,以便比较两个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中提取一个特定的完整块(),如下所示?在

^{pr2}$

Tags: 文件name标记文本statsxmlyesplayer
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

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

^{pr2}$

编辑请注意,要比较元素,这不一定是最佳方法。 另一个选项请参见here。在

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

相关问题 更多 >

    热门问题