使用 python 提取完整的 XML 块
Extract complete XML block using python
是否可以使用 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>
使用 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。
发现 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>
是否可以使用 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>
使用 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。
发现 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>