wuf*_*uff 3 python xml parsing xml-parsing python-2.7
我有一个类似于以下代码的 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>
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用 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']
Run Code Online (Sandbox Code Playgroud)
这是一个使用示例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']
Run Code Online (Sandbox Code Playgroud)
两者都打印:
49.8696518 -80.0973129
Run Code Online (Sandbox Code Playgroud)
BeautifulSoup就格式良好的 xml 结构而言,它更宽容(请参阅,我不得不稍微编辑 xml 以使事情适用于ElementTree),而且实际上使用起来要容易得多。
希望有帮助。
| 归档时间: |
|
| 查看次数: |
6956 次 |
| 最近记录: |