我试图从一个文件(file1.xml)中获取两个元素,并将它们写入另一个文件(file2.xml)的末尾。我可以让它们打印出来,但我试图将它们写入file2.xml!帮助!
filename = "file1.xml"
appendtoxml = "file2.xml"
output_file = appendtoxml.replace('.xml', '') + "_editedbyed.xml"
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(filename, parser)
etree.tostring(tree)
root = tree.getroot()
a = root.findall(".//Device")
b = root.findall(".//Speaker")
for r in a:
print etree.tostring(r)
for e in b:
print etree.tostring(e)
NewSub = etree.SubElement (root, "Audio(just writes audio..")
print NewSub
我希望将a,b的结果添加到根目录中outputfile.xml的末尾。
答案 0 :(得分:1)
root.append(elt)
将元素elt
附加到root
。tree.write
将新树写入文件(例如appendtoxml
):注意:上面的链接指向标准中xml.etree
的文档
图书馆。由于lxml
的API尝试与标准库兼容
xml.etree
,标准库文档也适用于lxml
(at
至少这些方法)。有关位置的信息,请参阅http://lxml.de/api.html
API不同。
import lxml.etree as ET
filename = "file1.xml"
appendtoxml = "file2.xml"
output_file = appendtoxml.replace('.xml', '') + "_editedbyed.xml"
parser = ET.XMLParser(remove_blank_text=True)
tree = ET.parse(filename, parser)
root = tree.getroot()
out_tree = ET.parse(appendtoxml, parser)
out_root = out_tree.getroot()
for path in [".//Device", ".//Speaker"]:
for elt in root.findall(path):
out_root.append(elt)
out_tree.write(output_file, pretty_print=True)
如果file1.xml
包含
<?xml version="1.0"?>
<root>
<Speaker>boozhoo</Speaker>
<Device>waaboo</Device>
<Speaker>anin</Speaker>
<Device>gigiwishimowin</Device>
</root>
和file2.xml
包含
<?xml version="1.0"?>
<root>
<Speaker>jubal</Speaker>
<Device>crane</Device>
</root>
然后file2_editedbyed.xml
将包含
<root>
<Speaker>jubal</Speaker>
<Device>crane</Device>
<Device>waaboo</Device>
<Device>gigiwishimowin</Device>
<Speaker>boozhoo</Speaker>
<Speaker>anin</Speaker>
</root>