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?
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.
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.
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.
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>
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With