【问题标题】:Problem parsing XML document with namespaces using Python lxml使用 Python lxml 解析带有命名空间的 XML 文档时出现问题
【发布时间】:2021-01-29 19:29:29
【问题描述】:

使用 Python lxml 库,我正在尝试解析 XML 文档,如下所示:

<ns:searchByScientificNameResponse xmlns:ns="http://itis_service.itis.usgs.gov">
<ns:return xmlns:ax21="http://data.itis_service.itis.usgs.gov/xsd" xmlns:ax23="http://metadata.itis_service.itis.usgs.gov/xsd" xmlns:ax26="http://itis_service.itis.usgs.gov/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax21:SvcScientificNameList">
<ax21:scientificNames xsi:type="ax21:SvcScientificName">
<ax21:tsn>26339</ax21:tsn>
<ax21:author>L.</ax21:author>
<ax21:combinedName>Vicia faba</ax21:combinedName>
<ax21:kingdom>Plantae</ax21:kingdom>
<ax21:unitInd1 xsi:nil="true" />
<ax21:unitInd2 xsi:nil="true" />
<ax21:unitInd3 xsi:nil="true" />
<ax21:unitInd4 xsi:nil="true" />
<ax21:unitName1>Vicia</ax21:unitName1>
<ax21:unitName2>faba</ax21:unitName2>
<ax21:unitName3 xsi:nil="true" />
<ax21:unitName4 xsi:nil="true" />
</ax21:scientificNames>
</ns:return>
</ns:searchByScientificNameResponse>

具体来说,我想获取“ax21:tsn”元素的值(本例中为整数26339)。

我尝试了herehere 的答案,但没有成功。这是我的代码:

import lxml.etree as ET

tree = ET.parse("sample.xml")
#print(ET.tostring(tree))

namespaces = {'ax21': 'http://data.itis_service.itis.usgs.gov/xsd'} 
tsn = tree.find('scientificNames/tsn', namespaces)
print(tsn)

它什么也不返回。使用 xpath 有一种非常聪明的方法吗?

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    两个问题:

    1. scientificNames 不是根元素的直接子元素;是孙子。

    2. 您需要在 XPath 表达式中使用 ax21 前缀。

    以下作品:

    tsn = tree.find('.//ax21:scientificNames/ax21:tsn', namespaces)
    

    或者简单地说:

    tsn = tree.find('.//ax21:tsn', namespaces)
    

    【讨论】:

    • 但它似乎不适用于“findall()”。
    • 不确定你的意思。请注意,findall 返回一个列表,而 find 返回单个元素。
    • 这将返回一个空列表:common_names = tree.findall(".//ax21:commonNames:ax21:commonName", namespaces)
    • 请发布一个新问题。
    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多