2011-07-22 54 views
2

添加元素有什麼辦法使用「路徑」添加到XML文檔一堆的條目是這樣的:它會自動創建所有必要是否有任何XML解析器,允許通過路徑蟒蛇

element = xmldoc.createElement("Work\\MainProject\\prj\\project.vcproj") 
xmldoc.appendChild(element) 

xml文件中的條目?

非常感謝, 羅馬

回答

1

我不知道如果這正是你在找什麼(這是一個有點不清楚什麼是「一切必要的條目」的意思)。無論如何,這裏是如何基於使用ElementTree(Python 2.6測試)的「路徑字符串」創建兩種XML層次結構。注意:minidom並不是真的必要;它只用於漂亮的打印。

from xml.etree.ElementTree import Element, SubElement, tostring 
from xml.dom.minidom import parseString 

def deep(tags): 
    """Create a deep hierarchy with tags[0] as the root and 
    tags[-1] as the sole leaf node""" 
    root = Element(tags[0]) 
    parent = root 
    for tag in tags[1:]: 
     elem = SubElement(parent, tag) 
     parent = elem 
    return root 

def shallow(tags): 
    """Create a shallow hierarchy with tags[0] as the root and 
    the other items as direct children""" 
    root = Element(tags[0]) 
    for tag in tags[1:]: 
     elem = SubElement(root, tag) 
    return root 

def pprint(s): 
    dom = parseString(s) 
    return dom.toprettyxml(indent=" ") 

if __name__ == '__main__': 
    p = "Work/MainProject/prj/project.vcproj" 
    taglist = p.split("/") 

    d = deep(taglist) 
    print pprint(tostring(d)) 

    s = shallow(taglist) 
    print pprint(tostring(s)) 

=>

<?xml version="1.0" ?> 
<Work> 
<MainProject> 
    <prj> 
    <project.vcproj/> 
    </prj> 
</MainProject> 
</Work> 

<?xml version="1.0" ?> 
<Work> 
<MainProject/> 
<prj/> 
<project.vcproj/> 
</Work>