使用XPath在python中解析 xml



我试图用内置的XML模块和元素树解析Python中的XML文件,但无论我根据文档尝试做什么,它都没有给我所需要的。我试图提取所有的标签到列表

<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>testPicklist__c</fullName>
<externalId>false</externalId>
<label>testPicklist</label>
<required>false</required>
<trackFeedHistory>false</trackFeedHistory>
<type>Picklist</type>
<valueSet>
<restricted>true</restricted>
<valueSetDefinition>
<sorted>false</sorted>
<value>
<fullName>a 32</fullName>
<default>false</default>
<label>a 32</label>
</value>
<value>
<fullName>23 432;:</fullName>
<default>false</default>
<label>23 432;:</label>
</value>

,这里是示例代码,我不能得到的工作。它是非常基本的,我所有的问题是xpath。

from xml.etree.ElementTree import ElementTree
field_filepath= "./testPicklist__c.field-meta.xml"
mydoc = ElementTree()
mydoc.parse(field_filepath)
root = mydoc.getroot()
print(root.findall(".//value")
print(root.findall(".//*/value")
print(root.findall("./*/value")

由于根元素具有属性xmlns="http://soap.sforce.com/2006/04/metadata",因此文档中的每个元素都属于该名称空间。所以你实际上是在寻找{http://soap.sforce.com/2006/04/metadata}value元素。

要在本文档中搜索所有<value>元素,您必须在findall()函数中指定namespace参数

from xml.etree.ElementTree import ElementTree
field_filepath= "./testPicklist__c.field-meta.xml"
mydoc = ElementTree()
mydoc.parse(field_filepath)
root = mydoc.getroot()
# get the namespace of root
ns = root.tag.split('}')[0][1:]
# create a dictionary with the namespace
ns_d = {'my_ns': ns}
# get all the values
values = root.findall('.//my_ns:value', namespaces=ns_d)
# print the values
for value in values:
print(value)

输出:

<Element '{http://soap.sforce.com/2006/04/metadata}value' at 0x7fceea043ba0>
<Element '{http://soap.sforce.com/2006/04/metadata}value' at 0x7fceea043e20>

或者你可以直接搜索{http://soap.sforce.com/2006/04/metadata}value

# get all the values
values = root.findall('.//{http://soap.sforce.com/2006/04/metadata}value')

最新更新