我想获取xml文件中每个元素的xpath。
xml文件:
<root
xmlns="http://www.w3.org/TR/html4/"
xmlns:h="http://www.w3schools.com/furniture">
<table>
<tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</tr>
</table>
</root>
python代码:由于默认名称空间中不允许使用null前缀,因此我使用了自己的前缀。
from lxml import etree
root=etree.parse(open("MyData.xml",'r'))
ns={'df': 'http://www.w3.org/TR/html4/', 'types': 'http://www.w3schools.com/furniture'}
for e in root.iter():
b=root.getpath(e)
print b
r=root.xpath(b,namespaces=ns)
#i need both b and r here
xpath像这样(输出b)
/*
/*/*[1]
/*/*[1]/*[1]
/*/*[1]/*[1]/h:td
我无法正确获取具有默认名称空间的元素的xpath,对于那些元素名称,它显示为*。如何正确获取xpath?
您可以使用getelementpath
,它始终以Clark表示法返回元素,并手动替换名称空间:
x = """
<root
xmlns="http://www.w3.org/TR/html4/"
xmlns:h="http://www.w3schools.com/furniture">
<table>
<tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</tr>
</table>
</root>
"""
from lxml import etree
root = etree.fromstring(x).getroottree()
ns = {'df': 'http://www.w3.org/TR/html4/', 'types': 'http://www.w3schools.com/furniture'}
for e in root.iter():
path = root.getelementpath(e)
root_path = '/' + root.getroot().tag
if path == '.':
path = root_path
else:
path = root_path + '/' + path
for ns_key in ns:
path = path.replace('{' + ns[ns_key] + '}', ns_key + ':')
print(path)
r = root.xpath(path, namespaces=ns)
print(r)
显然,此示例显示了getelementpath
返回相对于根节点的路径,例如.
和,dt:table
而不是/df:root
and /df:root/df:table
,因此我们使用tag
根元素的手动构建完整路径。
输出:
/df:root
[<Element {http://www.w3.org/TR/html4/}root at 0x37f5348>]
/df:root/df:table
[<Element {http://www.w3.org/TR/html4/}table at 0x44bdb88>]
/df:root/df:table/df:tr
[<Element {http://www.w3.org/TR/html4/}tr at 0x37fa7c8>]
/df:root/df:table/df:tr/types:td[1]
[<Element {http://www.w3schools.com/furniture}td at 0x44bdac8>]
/df:root/df:table/df:tr/types:td[2]
[<Element {http://www.w3schools.com/furniture}td at 0x44bdb88>]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句