Python从单个标记解析XML变量

2024-09-30 05:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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>

我试过用多米尼多姆,但如何从XML文件中轻松地解析出lat和lng变量值呢?在

提前感谢您的帮助!在


Tags: 文件代码reportphonexmlpublicnumat
2条回答

您需要使用XML解析器,如ElementTreeBeautifulSoup或{a3}。在

下面是一个使用标准库中的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的示例:

^{pr2}$

两种印刷品:

49.8696518 -80.0973129

就格式良好的xml结构而言,BeautifulSoup更为宽容(请参见,我不得不编辑xml以使ElementTree正常工作),而且它实际上更容易使用。在

希望有帮助。在

Pyparsing有一个从HTML标记中提取属性的内置方法,而不必为整个页面构建完整的对象模型。在

html = """
<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="">

I've tried using dom.minidom, but how can I easily parse out the lat and lng variable values fro
<spotter num="0188" report_at="2014-03-15 20:11:25" lat="59.8696518" lng="-82.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="addu@nnu.nne" first="" last="">

"""

from pyparsing import makeHTMLTags

spotterTag, spotterEndTag = makeHTMLTags("spotter")

for spotter in spotterTag.searchString(html):
    print spotter.report_at
    print spotter.num
    print spotter.lat
    print spotter.lng
    print spotter.email
    print

印刷品

^{pr2}$

相关问题 更多 >

    热门问题