我有一个类似于下面代码的 XML 文件:
<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129"callsign="wxman132" active="1" public="" gps="0" phone="" email="addu@nnu.nne" first="" last=""></spotter>
我试过使用 dom.minidom,但我怎样才能轻松地从 XML 文件中解析出 lat 和 lng 变量值?
提前感谢您的帮助!
最佳答案
您需要使用 XML 解析器,例如 ElementTree , BeautifulSoup或 lxml .
这是一个使用标准库中的 ElementTree
的示例:
from xml.etree import ElementTree as ET
tree = ET.fromstring("""
<test>
<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="addu@nnu.nne" first="" last=""/>
</test>""")
spotter = tree.find('.//spotter')
print spotter.attrib['lat'], spotter.attrib['lng']
这是一个使用 BeautifulSoup
的例子:
from bs4 import BeautifulSoup
data = '<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="addu@nnu.nne" first="" last=""/>'
soup = BeautifulSoup(data)
spotter = soup.spotter
print spotter['lat'], spotter['lng']
同时打印:
49.8696518 -80.0973129
BeautifulSoup
更宽容,就格式良好的 xml 结构而言(看,我不得不稍微编辑 xml 以使 ElementTree
工作),并且它实际上更容易使用。
希望对您有所帮助。
关于Python 从单个标签解析 XML 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599261/