如何使用 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)
您假设 username
是 location
的属性,但事实并非如此。它是一个子节点,它包含另一个子注释,即文本。 Minidom 非常麻烦,所以除非你 真的 必须使用它(想到安全原因)我会建议你使用 xml.etree.ElementTree
更新
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)
使用 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)
您假设 username
是 location
的属性,但事实并非如此。它是一个子节点,它包含另一个子注释,即文本。 Minidom 非常麻烦,所以除非你 真的 必须使用它(想到安全原因)我会建议你使用 xml.etree.ElementTree
更新
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)