【问题标题】:Iterate through XML child of a child tags in Python在 Python 中遍历子标签的 XML 子代
【发布时间】:2015-07-14 23:36:00
【问题描述】:

目前,我有一个 XML 文件。我想说,如果字符串是this,则打印与this 关联的所有子元素。我已经记录了一些我尝试过的代码。我正在使用内置的元素树。

XML

<commands>
    <command name="this" type="out" major="0x1" minor="0x0">
        <data bytes="1-0" descrip=" ID"></data>
        <data bytes="3-2" descrip=" ID"></data>
        <data bytes="5-4" descrip=" ID"></data>
        <data bytes="7-6" descrip="  Code"></data>
        <data bytes="12-8" descrip=" Revision"></data>
        <data bytes="13" descrip=" Version"></data>
        <data bytes="14" descrip="   Mask"></data>
        <data bytes="15" descrip="Reserved"></data>
        <data bytes="17-16" descrip="   Windows"></data>
        <data bytes="19-18" descrip=" of Write Flush Addresses"></data>
    </command>
</commands>

解析名称的示例代码

tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])

我基本上是想深入研究并打印命令名称的子标签。

【问题讨论】:

  • 你能举例说明你的预期输出吗?您当前的代码不会尝试返回我是您的预期输出,即所有data 节点。
  • ID、ID、ID、代码、修订...等

标签: python xml parsing


【解决方案1】:

你必须得到孩子的孩子并遍历所有的孙子

tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])    
        for grandchild in child.getchildren():
            print str(grandchild.attrib['bytes'])
            print str(grandchild.attrib['descrip'])

或者如果你想打印完整的 XML 行,你可以这样做:

print ET.tostring(grandchild).strip()

【讨论】:

  • 嗯,它似乎并没有实际打印值
  • 那么你的 if 语句有问题,因为它对我有用
  • 嗯,很奇怪。我从字面上复制并粘贴了您的代码。
  • 已弃用的功能也
  • getchildren 已弃用
猜你喜欢
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2015-01-11
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
相关资源
最近更新 更多