Is there any way to add to xml document a bunch of entries using "path" like this:
element = xmldoc.createElement("Work\\MainProject\\prj\\project.vcproj")
xmldoc.appendChild开发者_运维问答(element)
Which will automatically create all necessary entries in xml file?
Thanks a lot, Roman
I'm not sure if this is exactly what you are looking for (it's a bit unclear what "all necessary entries" means). Anyway, here is how you can create two kinds of XML hierarchies based on a "path string" using ElementTree (tested with Python 2.6). Note: minidom is not really necessary; it is only used for pretty-printing.
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>
精彩评论