Anekdotin
Anekdotin

Reputation: 1591

LXML add an element into root

Im trying to take two elements from one file (file1.xml), and write them onto the end of another file (file2.xml). I am able to get them to print out, but am stuck trying to write them onto file2.xml! Help !

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

I want the results of a, b to be added onto the end of outputfile.xml in the root.

Upvotes: 0

Views: 4497

Answers (1)

unutbu
unutbu

Reputation: 879421

  • Parse both the input file and the file you wish to append to.
  • Use root.append(elt) to append Element, elt, to root.
  • Then use tree.write to write the new tree to a file (e.g. appendtoxml):

Note: The links above point to documentation for xml.etree from the standard library. Since lxml's API tries to be compatible with the standard library's xml.etree, the standard library documentation applies to lxml as well (at least for these methods). See http://lxml.de/api.html for information on where the APIs differ.


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)

If file1.xml contains

<?xml version="1.0"?>
<root>
<Speaker>boozhoo</Speaker>
<Device>waaboo</Device>
<Speaker>anin</Speaker>
<Device>gigiwishimowin</Device>
</root>

and file2.xml contains

<?xml version="1.0"?>
<root>
<Speaker>jubal</Speaker>
<Device>crane</Device>
</root>

then file2_editedbyed.xml will contain

<root>
  <Speaker>jubal</Speaker>
  <Device>crane</Device>
  <Device>waaboo</Device>
  <Device>gigiwishimowin</Device>
  <Speaker>boozhoo</Speaker>
  <Speaker>anin</Speaker>
</root>

Upvotes: 1

Related Questions