Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert xml node in specific location

Tags:

python

xml

lxml

I would like to build the following xml:

<Item>
    <Name>Hello</Name>
    <Date>2014-01-01</Date>
    <Hero>1</Helo>
</Item>

Given the following code structure, how would I insert the <Date> node before the hero node?

item = etree.SubElement(self.xml_node, 'Item')
etree.SubElement(item, 'Name').text = 'Hello'
etree.SubElement(item, 'Hero').text = 1
# Now, how to insert the 'Date' element before the Hero element?
like image 1000
David542 Avatar asked Jun 05 '15 19:06

David542


People also ask

Does XML node order matter?

This is why in practice some XML elements can appear in any order without change of meaning, and the same is true for the content of some JSON arrays. Therefore it is important as part of the definition of any data format to know whether or not the order is significant.

What tells where exactly a particular node is located in the XML document?

Location path specifies the location of node in XML document. This path can be absolute or relative. If location path starts with root node or with '/' then it is an absolute path. Following are few of the example locating the elements using absolute path.

How do I find specific nodes in XML?

To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string.


1 Answers

Using etree.SubElement always appends the subelement to the end of the parent item. So instead, to insert a new element at a particular location, use item.insert(pos, subelement):

import lxml.etree as etree
xml_node = etree.Element("node")
item = etree.SubElement(xml_node, 'Item')
etree.SubElement(item, 'Name').text = 'Hello'
etree.SubElement(item, 'Hero').text = '1'
etree.SubElement(item, 'Date').text = '2014-01-01'
item.insert(1, item[-1])
print(etree.tostring(xml_node, pretty_print=True))

yields

<node>
  <Item>
    <Name>Hello</Name>
    <Date>2014-01-01</Date>
    <Hero>1</Hero>
  </Item>
</node>

Each node in an ElementTree can occur at only one place. So although

etree.SubElement(item, 'Date').text = '2014-01-01'

places the <Date> node at the end of <item>,

item.insert(1, item[-1])

moves the last node in item, i.e. the <Date> node, to position 1 (making it the second child in <Item>).

like image 120
unutbu Avatar answered Oct 18 '22 00:10

unutbu