【问题标题】:Fecth data of specific tag from xml using xml.etree使用 xml.etree 从 xml 中获取特定标签的数据
【发布时间】:2020-06-08 06:13:51
【问题描述】:

我正在尝试从看起来有点像这样的 xml 数据中获取 names

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Major Version</key><integer>1</integer>
    <key>Minor Version</key><integer>1</integer>
    <dict>
        <key>369</key>
        <dict>
            <key>Track ID</key><integer>369</integer>
            <key>Name</key><string>Another One Bites The Dust</string>
            <key>Artist</key><string>Queen</string>
        </dict>
        <key>371</key>
        <dict>
            <key>Track ID</key><integer>371</integer>
            <key>Name</key><string>Asche Zu Asche</string>
            <key>Artist</key><string>Rammstein</string>
        </dict>

我正在尝试以下代码,它为我提供了 &lt;key&gt; tag 的文本值。考虑到第一个标签的文本值是 Name ,我需要第二个标签的文本值。 所以需要的输出是 Another One Bites The DustAsche Zu Asche

    import xml.etree.ElementTree as ET
    stuff = ET.parse(fname)
    all = stuff.findall('dict/dict/dict')
    for item in all:
      for child in item :
        if child.tag == 'key' and child.text == 'Name':
           print(child.text)

【问题讨论】:

    标签: python-3.x xml xml.etree


    【解决方案1】:

    要使用 ET,试试这个:

    all = stuff.findall('dict/dict')
    for item in all:
        children = item.findall('.//key')
        for child in children:
            if child.text=="Name":
                print(item.find('.//string').text)
    

    最简单的方法是使用 lxml 而不是 xml.etree,因为 lxml 具有更好的 xpath 支持。这样就很简单了:

    from lxml import etree
    stuff = ET.parse(fname)
    all = stuff.xpath('//dict/dict/key[.="Name"]/following-sibling::*[1]')
    for a in all:
        print(a.text)
    

    在这两种情况下,输出都是:

    Another One Bites The Dust
    Asche Zu Asche
    

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多