使用 Python lxml 解析带有命名空间的 XML 文档时出现问题
Problem parsing XML document with namespaces using Python lxml
使用 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)。
我尝试了 here and 的答案,但没有成功。这是我的代码:
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)
只是 returns 没什么。是否有使用 xpath 执行此操作的真正智能方法?
两个问题:
scientificNames
不是根元素的直接子元素;是孙子
您需要在 XPath 表达式中使用 ax21
前缀。
以下作品:
tsn = tree.find('.//ax21:scientificNames/ax21:tsn', namespaces)
或者简单地说:
tsn = tree.find('.//ax21:tsn', namespaces)
使用 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)。
我尝试了 here and
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)
只是 returns 没什么。是否有使用 xpath 执行此操作的真正智能方法?
两个问题:
scientificNames
不是根元素的直接子元素;是孙子您需要在 XPath 表达式中使用
ax21
前缀。
以下作品:
tsn = tree.find('.//ax21:scientificNames/ax21:tsn', namespaces)
或者简单地说:
tsn = tree.find('.//ax21:tsn', namespaces)