http://www.cnblogs.com/bluescorpio/archive/2013/06/09/3127964.html
http://blog.csdn.net/u012063703/article/details/51754665
http://www.jianshu.com/p/f446663c970f
1. 判断是否有子元素或子节点
使用len(element),这更清楚,也不容易犯错。
>>>
print
(etree.iselement(root))
# test if it's some kind of Element
True
>>>
if
len
(root):
# test if it has children
...
print
(
"The root element has children"
)
The root element has children
#!/usr/bin/env python
import os
import sys
import re
from lxml import etree
tree1 = etree.parse(r'default.xml')
root1 = tree1.getroot()
root = etree.Element('manifest')
#for child in root1.iter('project'):
for child in root1:
if not isinstance(child, etree._Comment):
if len(child):
child_node = etree.SubElement(root, child.tag, child.attrib)
for node in child.getchildren():
etree.SubElement(child_node, node.tag, node.attrib)
print node.tag, node.attrib
else:
etree.SubElement(root, child.tag, child.attrib)
else:
root.append(etree.Comment(child.text))
tree = etree.ElementTree(root)
tree.write('mytest.xml', pretty_print=True, xml_declaration=True, encoding="utf-8", method='xml')
"""
remote = etree.Element('remote', fetch="..", name="MTK", review="10.75.10.90:8080")
default = etree.Element('default', {'remote': "MTK", 'revision': "E1/MTK/MT6737M/8.0/dev", 'sync-c': 'true', 'sync-j': '4'})
#root.append(remote)
#root.append(default)
root.extend([remote, default])
"""
"""
etree.SubElement(root, 'remote', fetch="..", name="MTK", review="10.75.10.90:8080")
etree.SubElement(root, 'default', {'remote': "MTK", 'revision': "E1/MTK/MT6737M/8.0/dev", 'sync-c': 'true', 'sync-j': '4'})
etree.SubElement(root, 'project', groups="device,fugu,broadcom_pdk,pdk", name="MTK/device/asus/fugu", path="LINUX/android/device/asus/fugu", revision="22d134832ae86e1df7f2ceee7ce0fbb56155050f", upstream="MTK/MT6737M/8.0/PRS.2017.06.10.10.00")
xml_data = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding="utf-8")
print xml_data
print 'write xml...'
tree = etree.ElementTree(root)
tree.write('mytest.xml', pretty_print=True, xml_declaration=True, encoding="utf-8")
#with open('your.xml', 'w') as f:
# f.write(xml_data)
"""