简体   繁体   中英

Parsing Xml file with ElementTree, no attributes shown

I have a xml file composed of different part:

<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>

If I use tree.iter() to iterate i can get access to any keys, values using for example:

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)

I will get in output:

  aa 
  bo

but i want to separate the iteration by part and above the parsing is done line by line. I've tried tree.iter('part') which separates the iteration by part but I can't get access to the keys, class and values with the same methods as before... node.attrib is empty.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM