Extracting String from XML files with loop in Python

为君一笑 提交于 2021-01-07 06:48:46

问题


enter image description here

I have 14 different XML files like this and I'm trying to get ActionUnit Number values (ex. 45 and 5). I need to do it for the other 13 XML files too with a loop. After that, I need to create subfolders for each value that I extracted. I tried a code for value extraction but I get none as a result;

import xml.etree.cElementTree as ET

tree= ET.ElementTree(file=r'C:\Users\LME_s\Desktop\python quiz\Sessions\1\S001-001-oao_aucs.xml')
root= tree.getroot()
for chld in root:
   print (chld.get('ActionUnit Number'))

回答1:


Your question is actually few questions... Here is how to extract the data you need from the xml.

import xml.etree.ElementTree as ET

XML = '''<ActionUnitCoding>
            <ActionUnit Number="45"></ActionUnit>
            <ActionUnit Number="5"></ActionUnit>
        </ActionUnitCoding>'''
root = ET.fromstring(XML)
numbers = [e.attrib['Number'] for e in root.findall('.//ActionUnit')]
print(numbers)

output

['45', '5']


来源:https://stackoverflow.com/questions/65276888/extracting-string-from-xml-files-with-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!