如何使用 fromstring 进行 ElementTree 使用 python 的 xml 解析?
how to use fromstring for xml parsing by ElementTree using python?
xml代码是这样的
<foo>
<bar key="value">text</bar>
</foo>
Python代码为:
import xml.etree.ElementTree as ET
xml=ET.fromstring(contents)
xml.find('./bar').attrib['key']
输出:'value'
上面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']
xml代码是这样的
<foo>
<bar key="value">text</bar>
</foo>
Python代码为:
import xml.etree.ElementTree as ET
xml=ET.fromstring(contents)
xml.find('./bar').attrib['key']
输出:'value'
上面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']