4

I wonder if it is better add an element by opening file, search 'good place' and add string which contains xml code. Or use some library... i have no idea. I know how can i get nodes and properties from xml through for example lxml but what's the simpliest and the best way to add?

2 Answers 2

4

You could use lxml.etree.Element to make the xml node(s), and use append or insert to attach them into xml document:

data='''\
<root>
<node1>
  <node2 a1="x1"> ... </node2>
  <node2 a1="x2"> ... </node2>
  <node2 a1="x1"> ... </node2>
</node1>
</root>
'''
doc = lxml.etree.XML(data)
e=doc.find('node1')
child = lxml.etree.Element("node3",attrib={'a1':'x3'})
child.text='...'
e.insert(1,child)
print(lxml.etree.tostring(doc))

yields:

<root>
    <node1>
      <node2 a1="x1"> ... </node2>
      <node3 a1="x3">...</node3><node2 a1="x2"> ... </node2>
      <node2 a1="x1"> ... </node2>
    </node1>
    </root>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, lxml is very simple and clarify.
1

The safest way to add nodes to an XML document is to load it into a DOM, add the nodes programmatically and write it out again. There are several Python XML libraries. I have used minidom, but I have no reason to recommend it specifically over the others.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.