【问题标题】:In Python, how can I inspect a specific section of XML and extract the node text?在 Python 中,如何检查 XML 的特定部分并提取节点文本?
【发布时间】:2018-01-08 18:08:07
【问题描述】:

我正在使用 minidom 检查包含调试键列表的 XML。 XML 示例如下:

<Shortcuts>
  <Item>
    <CommandName>DebugCommandName_1</CommandName>
    <ShortcutKeys>
      <Item>
        <Keys>
          <Item>KEY_1</Item>
          <Item>KEY_2</Item>
        </Keys>
      </Item>
    </ShortcutKeys>
  </Item>
...
  <Item>
    <CommandName>DebugCommandName_2</CommandName>
    <ShortcutKeys>
      <Item>
        <Keys>
          <Item>KEY_3</Item>
        </Keys>
      </Item>
      <Item>
        <Keys>
          <Item>KEY_4</Item>
        </Keys>
      </Item>
    </ShortcutKeys>
  </Item>
</Shortcuts>

由于我无法控制的原因,我将无法要求将传入 XML 的格式更改为更加一致,因此我必须考虑文档的 ShortcutKeys 部分的布局以及多个 Item到处都是子元素。

用minidom解析XML,然后我用下面的Python来提取内容:

for item in parsedKeyComboFile.getElementsByTagName("Item"):
if (item.getElementsByTagName("CommandName").length > 0): 
    commandName = item.getElementsByTagName("CommandName")[0].childNodes[0].nodeValue
    print(commandName)
elif (item.getElementsByTagName("Keys").length > 0):
    keyCombo = item.getElementsByTagName("Item")[0].childNodes[0].nodeValue
    print(keyCombo)

我最终会将此信息添加到字典中,但现在我得到的上述 XML 的打印结果是:

DebugCommandName_1
KEY_1
DebugCommandName_2
KEY_3
KEY_4

当我想要的是:

DebugCommandName_1
KEY_1 KEY_2
DebugCommandName_2
KEY_3 KEY_4

(我意识到我没有正确格式化键的打印以实现单行输出。这里的关键不是跳过 KEY_2 项。)

我知道 keyCombo= 行中的 [0] 将我限制为 Keys 中 Item 的第一次出现。

那么,有没有办法让我检查一个顶级 Item 及其所有子元素,提取该顶级 Item 中的单个 CommandName 和所有 Keys 项目,然后再进入下一个顶级项目并重复该过程?到目前为止,我完全没有做到这一点。

我应该使用 ElementTree 吗?

非常感谢。

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    我没有使用minidom 的经验,建议

    不推荐使用它,你可能想使用xml.etree.ElementTree

    --来自minidom标签信息

    如果您可以改用xml.etree.ElementTree,这可能是一种直截了当的方法:

    import xml.etree.ElementTree as ET
    tree = ET.parse('example.xml')
    root = tree.getroot()  # unused variable in this example
    
    for elem in tree.iter():
        if elem.tag == 'CommandName':
            print(elem.text)
        if elem.tag == 'Keys': 
            for item in elem:
                print(item.text)
    

    打印

    DebugCommandName_1
    KEY_1
    KEY_2
    DebugCommandName_2
    KEY_3
    KEY_4
    

    或者,如果您想要每个 &lt;Keys&gt; 标签的列表:

    if elem.tag == 'Keys':
        print([item.text for item in elem])
    

    打印:

    DebugCommandName_1
    ['KEY_1', 'KEY_2']
    DebugCommandName_2
    ['KEY_3']
    ['KEY_4']
    

    【讨论】:

    • 非常好,感谢您指出我在 minidom 文档中明显遗漏的内容!
    【解决方案2】:

    由于我低于阈值,因此无法发表评论,因此请原谅我将其作为答案

    是的,您应该按照我在此处找到的链接使用元素树

    Python Minidom XML Query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-17
      • 2021-02-12
      • 1970-01-01
      • 2021-06-01
      • 2016-05-12
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多