python - 如何使用Python通过ElementTree使用fromstring进行xml解析?

标签 python xml python-2.7 elementtree

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 以 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']

关于python - 如何使用Python通过ElementTree使用fromstring进行xml解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277075/

相关文章:

python xlrd 字符串匹配

python - 如何使用python读取文件?

c# - Xml Linq Query(通过属性和属性值获取元素)

python - Odoo : Computed fields, 在某些情况下不更新?

python - 为什么导入模块会导致该模块在从站点包调用它时运行,但在本地调用它时却不会运行?

python - 将输出(上下文)嵌入保存在 word2vec(gensim 实现)中作为最终模型

javascript - 从钛合金选取器中获取选定行

java - android隐藏内部RelativeLayout防止 Activity 出现

python - 处理 urllib2 返回的 badstatusline(line)?

python - 使用 PyQGIS 从 POSTGIS 数据库中获取表名