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/