使用python提取完整的XML块
是否可以使用Python从XML文件中提取完整的XML文本块?我使用ElementTree和Python从XML中提取标记和值,以便比较2个XML文件。 但是,有可能提取XML块的整个文本吗 例如:使用python提取完整的XML块,python,xml,linux,elementtree,Python,Xml,Linux,Elementtree,是否可以使用Python从XML文件中提取完整的XML文本块?我使用ElementTree和Python从XML中提取标记和值,以便比较2个XML文件。 但是,有可能提取XML块的整个文本吗 例如: <stats> <player> <name>Luca Toni</name> <matches>47</matches> <goals>16</goals> <WC
<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>
托尼
47
16
对
阿尔贝托·吉拉迪诺
57
19
对
马里奥·巴洛特利
36
14
对
是否可以使用python(ElementTree)从上述XML中提取一个特定的完整块(),如下所示
托尼
47
16
对
使用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)
编辑注意,要比较元素,这不一定是最好的方法。
请参阅以获取另一个选项。发现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>
从lxml导入etree
node1=etree.parse(“azzurri.xml”)
e1=node1.xpath(“.//player”)缩进错误:意外缩进
对于e1中的ele1:
pl=ele1.xpath(“.//名称”)
对于pl中的pl1:
如果pl1.text==“卢卡·托尼”:
rl1=ele1.text+''.join(map(etree.tostring,ele1)).strip()
打印rl1
托尼
47
16
对
您想解析一个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>