繁体   English   中英

如何使用Minidom从python中的xml文件读取数据

[英]How to read data from xml file in python using minidom

什么是使用python从xml文件读取值的最佳(最简单)方法? 我是新手,并且尝试过使用minidom,但是不确定如何格式化脚本。

/tmp/text.xml中的XML:

<computer>
<location>
<username>FirsLast</username>
</location>
</computer>

我想解析用户名并将其用作变量。

这是我尝试过的:

#!/usr/bin/python

import xml.dom.minidom as minidom

doc = minidom.parse('/tmp/text.xml')
location = doc.getElementsByTagName('location')[0]
username = location.getAttribute('username')

print(username)

我什么都没有得到。 我希望看到FirsLast

从我的头顶:

import xml.dom.minidom as minidom
doc = minidom.parse('/tmp/tes.xml')
location = doc.getElementsByTagName('location')[0]
# If I recall carriage return and spaces are text nodes so we
# need to skip those
username = list(filter(lambda x: x.nodeType == minidom.Node.ELEMENT_NODE, location.childNodes))
print(username[0].firstChild.nodeValue)

您假设usernamelocation的属性,而不是location的属性。 这是一个子节点,其中包含另一个子注释,即文本。 Minidom非常麻烦,因此除非您真的需要使用它(出于安全考虑),我建议您使用xml.etree.ElementTree

UPDATE

Op请求使用ET的示例:

import xml.etree.ElementTree as ET
sample = """
<computer>
<location>
<username>FirsLast</username>
</location>
</computer>
"""
doc = ET.fromstring(sample)
username = doc.findall('./location/username')
print(username[0].text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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