# _*_ coding :'utf-8' _*_
'''
Created on 2013-8-13
@author: nohack
'''
from lxml import etree
#import xml.etree.ElementTree as etree
if __name__ == '__main__':
#root = etree.Element("root")
root = etree.Element("root",nsmap={'xsi': 'http://b.c/d'})
root.set("xsiinteresting", "totally")
child1 = etree.SubElement(root, "child1" )
child1.set("interesting", "totally")
child1.text = "TEXT"
child2 = etree.SubElement(root, "child2")
child2.set("Attr1", "myattr1")
child2.set("Attr2", "myattr2")
child3 = etree.SubElement(child2, "child3")
child3.text = "TEXT"
child4 = etree.SubElement(child2, "child4")
child4.text = "TEXT"
child5 = etree.SubElement(child2, "child5")
child6 = etree.SubElement(child5, "child6")
child6.text = "TEXT"
child7 = etree.SubElement(child5, "child7")
child7.text = "TEXT"
#root.append( etree.Element("child1") )
#root.append( etree.Element("child1", interesting="totally"))
#child2 = etree.SubElement(root, "child2")
#child3 = etree.SubElement(root, "child3")
#root.insert(0, etree.Element("child0"))
print etree.tostring(root, pretty_print=True)
# write to file:
tree = etree.ElementTree(root)
tree.write('TEST.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
theTEST.xml file :
<root xmlns:xsi="http://b.c/d" xsiinteresting="totally">
<child1 interesting="totally">TEXT</child1>
<child2 Attr1="myattr1" Attr2="myattr2">
<child3>TEXT</child3>
<child4>TEXT</child4>
<child5>
<child6>TEXT</child6>
<child7>TEXT</child7>
</child5>
</child2>
</root>
文件后缀名有几种可选的方式,但不可自定义,c++调用python解析xml时,会因为from lxml import etree出错,暂时未来得及解决