如何使用 python 获取具有默认命名空间的 xml 文件中所有元素的 xpath?

how to get xpath of all elements in xml file with default namespace using python?

我想获取 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代码: 由于默认命名空间中的空前缀是不允许的,我为此使用了自己的前缀。

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,它总是 returns 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 returns 相对于根节点的路径,像 .dt:table 而不是 /df:root/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>]