【问题标题】:Extract complete XML block using python使用python提取完整的XML块
【发布时间】:2018-11-28 04:57:48
【问题描述】:

是否可以使用 Python 从 XML 文件中提取完整的 XML 文本块?我正在使用 ElementTree 和 Python 从 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>

【问题讨论】:

  • 您想解析一个 xml 文档,获取一个片段并将该片段转回字符串?
  • 是的。我需要一个块的完整内容来将它与另一个文件中的类似内容进行比较

标签: python xml linux elementtree


【解决方案1】:

使用 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)

编辑请注意,比较元素,这不一定是最好的方法。 请参阅here 了解其他选项。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多