【问题标题】:How to read data from xml file in python using minidom如何使用minidom从python中的xml文件中读取数据
【发布时间】:2019-01-23 20:23:28
【问题描述】:

使用 python 从 xml 文件中读取值的最佳(re:最简单)方法是什么?我是新手,尝试过使用 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

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    从我的头顶:

    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 的一个属性,但事实并非如此。它是一个子节点,它包含另一个子注释,即文本。 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)
    

    【讨论】:

    • 我支持 xml.etree.ElementTree。我如何解析用户名?我设法通过使用“for child in root: print(child.tag, child.attrib)”来获取“位置”,但我不确定如何进一步深入获取“用户名”
    • 做到了!非常感谢!
    • ET 的优点是允许您使用 XPath,很高兴它有所帮助。
    • 相关问题 - 我可以稍后在脚本中将该值用作变量吗?如果我添加一行 's_username = (username[0].text)'
    • 当然,只是str,没什么特别的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多