【问题标题】:XML parsing python nestedXML解析python嵌套
【发布时间】:2019-03-19 18:28:25
【问题描述】:

我有以下 XML 文件:

<annotations count="1">
  <track id="0" label="Machine">
    <box frame="0" ><attribute id="8">act1</attribute></box>
    <box frame="1" ><attribute id="8">act2</attribute></box>
    <box frame="2" ><attribute id="8">act1</attribute></box>
  </track>
</annotations>

我想提取 frame 和 action inside 属性。例如我想要 (frame: 0 , act1), (frame: 1 , act2) ... 现在我正在做的是

root = xml.etree.ElementTree.parse(xml_file_path).getroot()

for track in root.iter('track'):
  for box in track.iter('box'):
    frame = box.get('frame')

我怎样才能获得相应的属性(act1,...,act 1)?

【问题讨论】:

    标签: python xml parsing


    【解决方案1】:

    您可以使用

    访问&lt;attribute id="8"&gt;act1&lt;/attribute&gt;
    box.find('attribute')
    

    为了得到你使用的行为:

    >>>box.find('attribute').text
    act1 # or act2
    

    python 文档是一个非常好的资源:@​​987654321@

    【讨论】:

    • 我之前也试过,但我得到的是 'NoneType' 对象没有属性 'text' 。我不明白为什么
    • 好的,问题是其中一行没有属性。
    【解决方案2】:

    您还可以使用数组表示法,如果您正在抓取或将其放入大量循环中,这可能会很有用

    root[0][0][0].text

    root[0][0][1].text 等等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      相关资源
      最近更新 更多