简体   繁体   English

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

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

I wanted to get xpath of each element in xml file. 我想在xml文件中获取每个元素的xpath。

xml file: 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 code: Since null prefix in default namespace is not allowed,i used my own prefix for that. 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

the xpath is like this(output b) xpath是这样的(输出b)

/*
/*/*[1]
/*/*[1]/*[1]
/*/*[1]/*[1]/h:td

i can't get the xpath correctly for elements having default namespace,it shows as * for those elements name. 我无法正确获取具有默认命名空间的元素的xpath,它对于那些元素名称显示为*。 How to get xpath correctly? 如何正确获取xpath?

You could use getelementpath , which always returns the elements in Clark notation, and replace the namespaces manually: 您可以使用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)

Obviously, this example shows that getelementpath returns paths relative to the root node, like . 显然,这个例子表明getelementpath返回相对于根节点的路径,比如. and dt:table instead of /df:root and /df:root/df:table , so we use the tag of the root element to manually construct the full path. dt:table而不是/df:root/df:root/df:table ,所以我们使用root元素的tag来手动构建完整路径。

Output: 输出:

/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>]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM