如何使用python读取xml文件?
我有一个这样的xml文件如何使用python读取xml文件?,python,xml,minidom,Python,Xml,Minidom,我有一个这样的xml文件 <?xml version="1.0" encoding="UTF-8"?> <Automation_Config> <Path> <Log>.\SERVER.log</Log> <Flag_Path>.\Flag</Flag_Path> <files>.\PO</files> </Path&g
<?xml version="1.0" encoding="UTF-8"?>
<Automation_Config>
<Path>
<Log>.\SERVER.log</Log>
<Flag_Path>.\Flag</Flag_Path>
<files>.\PO</files>
</Path>
</Automation_Config>
使用
ElementTree
:
import xml.etree.ElementTree as ET
tree = ET.parse('Config.xml')
root = tree.getroot()
print(root.findall('.//Log'))
输出:
pawel@pawel-XPS-15-9570:~/test$ python parse_xml.py
[<Element 'Log' at 0x7fb3f2eee9f
pawel@pawel-XPS-15-9570:~/test$python parse_xml.py
[如下:
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Automation_Config>
<Path>
<Log>.\SERVER.log</Log>
<Flag_Path>.\Flag</Flag_Path>
<files>.\PO</files>
</Path>
</Automation_Config>'''
root = ET.fromstring(xml)
for idx,log_element in enumerate(root.findall('.//Log')):
print('{}) Log value: {}'.format(idx,log_element.text))
请尝试使用我强烈建议不要使用xml.dom.minidom
。除非您有非常具体的需要使用非常简单和基本的W3C dom API,否则您希望使用。dom API旨在作为许多编程语言之间的最小共同点,许多编程语言的表达能力不如Python。因此,它是v使用ElementTree
API,获取第一个Log
元素的字符串内容就像tree=ET.parse(filename)
然后value=tree.find(.//Log”).text一样简单。
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Automation_Config>
<Path>
<Log>.\SERVER.log</Log>
<Flag_Path>.\Flag</Flag_Path>
<files>.\PO</files>
</Path>
</Automation_Config>'''
root = ET.fromstring(xml)
for idx,log_element in enumerate(root.findall('.//Log')):
print('{}) Log value: {}'.format(idx,log_element.text))
0) Log value: .\SERVER.log