我有一个 xml 文件中尚不存在的节点的 xpath,并且希望使用它来生成有问题的节点。我已经开始研究一个函数来做到这一点,但想知道是否有一个现有的库可以做到这一点并节省我一些时间?我目前正在使用 pyxml,但正在考虑将其移植到 ElementTree。所以为了澄清我想要:
root/foo/bar
Run Code Online (Sandbox Code Playgroud)
生产:
<root>
<foo>
<bar>
</bar>
</foo>
</root>
Run Code Online (Sandbox Code Playgroud)
我怀疑这样一个函数的行为对于一般情况没有足够好的定义,任何人都不会打扰,但我认为我会把它扔在那里以防万一。我还有该文件的 DTD(如果有帮助的话)。
没有找到任何准备好的东西,但使用 ElementTree (甚至另一个 xml 库 - 只是我更熟悉 ElementTree )应该或多或少简单。
下面的代码片段似乎适用于所需的 xpath 的有限子集:
# -*- coding: utf-8 -*-
from xml.etree import ElementTree as ET
def build_xpath(node, path):
components = path.split("/")
if components[0] == node.tag:
components.pop(0)
while components:
# take in account positional indexes in the form /path/para[3] or /path/para[location()=3]
if "[" in components[0]:
component, trail = components[0].split("[",1)
target_index = int(trail.split("=")[-1].strip("]"))
else:
component = components[0]
target_index = 0
components.pop(0)
found_index = -1
for child in node.getchildren():
if child.tag == component:
found_index += 1
if found_index == target_index:
node = child
break
else:
for i in range(target_index - found_index):
new_node = ET.Element(component)
node.append(new_node)
node = new_node
if __name__ == "__main__":
#Example
root = ET.Element("root")
build_xpath(root, "root/foo/bar[position()=4]/snafu")
print ET.tostring(root)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2346 次 |
| 最近记录: |