Skip to main content
 首页 » 编程设计

python之是否有任何 xml 解析器允许在 python 中按路径添加元素

2025年05月04日10三少

有什么方法可以像这样使用“路径”向 xml 文档添加一堆条目:

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

哪个会自动在 xml 文件中创建所有必要的条目?

非常感谢, 罗马

请您参考如下方法:

我不确定这是否正是您要查找的内容(有点不清楚“所有必要条目”的含义)。不管怎样,下面介绍了如何使用 ElementTree(使用 Python 2.6 测试)基于“路径字符串”创建两种 XML 层次结构。注意:minidom 并不是必须的;它仅用于 pretty-print 。

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>