2011-04-14 91 views
1

我有一个xml文件中的节点,该文件尚不存在,并且想用它来生成有问题的节点。我已经开始研究一个函数来做到这一点,但想知道是否有一个现有的库可以做到这一点,并节省了我一些时间?我目前正在使用pyxml,但正在考虑将其移植到ElementTree。因此,要澄清我想:如何在Python中使用xpath填充xml文件

root/foo/bar 

产生:

<root> 
    <foo> 
    <bar> 
    </bar> 
    </foo> 
</root> 

我怀疑的是,这样一个函数的行为是不是不够好,一般情况下定义的人,打扰你了,但想到我为了以防万一,请将它扔出去。如果这有帮助,我还有一个文件的DTD。

+0

乍一看,这似乎是不可能的创建基于XPath的“_stricto sensu_”这样的元素。例如,它会为'// foo/bar'生成什么? OTOH,它似乎有可能基于XPath的一个子集生成XML - 事实上它似乎是一个好主意。 – brandizzi 2011-04-14 15:22:04

回答

1

找不到任何东西准备好, 但它应该或多或少地直接使用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) 
+1

如何在这里处理属性? – 2014-10-07 14:25:57