【问题标题】:Parsing Xml file with ElementTree, no attributes shown使用 ElementTree 解析 Xml 文件,未显示属性
【发布时间】:2017-02-10 11:17:12
【问题描述】:

我有一个由不同部分组成的 xml 文件:

<part>
    <spec key="ID" value="aa" />
    <spec key="Family" value="bb" />
    <spec class="0" key="bb" type="desc" value="30" />
</part>
<part>
    <spec key="ID" value="bo" />
    <spec key="Family" value="bbc" />
    <spec class="1" key="bss" type="desc" value="30" />
</part>

如果我使用 tree.iter() 进行迭代,我可以访问任何键、值,例如:

tree = ET.parse(path)#path is the xml file.
for node in tree.iter():
   if node.attrib.get('key')=='ID':
      ID = node.attrib.get("value")
      print(ID)

我会得到输出:

  aa 
  bo

但我想按部分分开迭代,上面的解析是逐行完成的。 我试过 tree.iter('part') 将迭代部分分开,但我无法使用与以前相同的方法访问键、类和值... node.attrib 为空。

【问题讨论】:

标签: python xml-parsing elementtree


【解决方案1】:
tree = ET.parse(path)#path is the xml file.
   for node in tree.iter():
       for subnode in node.ter():
           if subnode.attrib.get('key')=='ID':
              ID = node.attrib.get("value")
              print(ID)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2012-02-07
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多