Python 从单个标签解析 XML 变量

标签 python xml parsing python-2.7 xml-parsing

我有一个类似于下面代码的 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 , BeautifulSouplxml .

这是一个使用标准库中的 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/

相关文章:

java - 将 XML 格式保存为字符串而不是文件

parsing - 括号如何与自定义数据类型一起使用?

python - 如何在Python3中检查用户输入?

python - 模仿 fileno() 和 select 的行为

python - 为什么我们在 tensorflow 的损失函数中需要 `int64` 作为 MNIST 标签?

java - 如何使用 FasterXML 库序列化 POJO 列表

python - IronPython:无法识别双关键字?

xml - 使用 XSLT 用 href 属性包装所有元素

Javascript JSON解析对象,一个对象属性未定义,不抛出任何错误

.net - 将 EDI 转换为 Xml