I have a situation where I want to add a particular element at the position and update if there is already present at the given position. Ex:
<items>
<productid />
<product_details>
<entry>
<key>?</key>
<value>?</value>
</entry>
</product_details>
</items>
Now say for an ex: I pass the position as 1 and want to add values to the Key and Value, consider
parent = product_details
position = 1
key = ProductName
value = Maggi
Then it should update the xml since there is entry/key & entry/value at position 1 already. i.e.,
<items>
<productid />
<product_details>
<entry>
<key>ProductName</key>
<value>Maggi</value>
</entry>
</product_details>
</items>
If I pass the position as 2, then it should be:
<items>
<productid />
<product_details>
<entry>
<key>?</key>
<value>?</value>
</entry>
<entry>
<key>ProductName</key>
<value>Maggi</value>
</entry>
</product_details>
</items>
Edit: So far what I tried honestly is inserting at the position. Since I'm very new to Python, I'm bit confused on how to achieve this. The below code is slightly modified version of what I got from SO only. Ex:
def to_xml(parent, xpath, value, index):
nodes = parent.xpath(xpath)
if nodes:
node = nodes[0]
else:
parts = xpath.split('/')
p = parent
for part in parts:
nodes = p.xpath(part)
if not nodes:
n = etree.XML("<%s/>" % part)
p.append(n)
p = n
else:
p = nodes[0]
node = p
node.text = str(value)