【问题标题】:how to use fromstring for xml parsing by ElementTree using python?如何使用 fromstring 通过 ElementTree 使用 python 进行 xml 解析?
【发布时间】:2017-05-31 06:18:28
【问题描述】:

xml代码是这样的

<foo>
<bar key="value">text</bar>
</foo>

Python 代码是:

import xml.etree.ElementTree as ET
xml=ET.fromstring(contents)
xml.find('./bar').attrib['key']

输出:'值'

上述python代码的内容位置必须放置什么才能将值作为输出?

如果我只写内容,它会给出一个错误,因为内容没有定义。

【问题讨论】:

  • 如果我在内容中写入整个大 xml 文件,仍然会弹出该行存在语法错误。

标签: python xml python-2.7 elementtree


【解决方案1】:

如果 XML 以triple-quoted string 的形式提供,它就可以工作。这允许您在字符串中包含未转义的引号。

import xml.etree.ElementTree as ET

contents = """
<foo>
<bar key="value">text</bar>
</foo>"""

xml = ET.fromstring(contents)
print xml.find('./bar').attrib['key']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2017-03-16
    相关资源
    最近更新 更多