Ok, I have a case where I need to add a tag to a certain other tag given an xpath.
Example xml:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<general>>
<services>
<land/>
<refuel/>
</services>
</general>
</asset>
<asset name="Test">
<general>
<Something/>
</general>
</asset>
</Assets>
I want to add a <missions>
tag to both assets. However, the second asset is missing the parent <services>
tag, which I want to add. Each asset tag is stored in a variable (say node1, node2).
I have the following xpath: xpath1 = services/missions
, which, due to the way my program works, I cannot simply store in a different form (i.e. i don't have a place to store just services
)
I need to check and see if the missions tag already exists, and, if so, do nothing. If the tag does not exist, I need to create it. If its parent does not exist, I need to create that too.
How can I do this simply by using the xpath string?
Edit: I want to base all this on a boolean value: i.e. val = true, then create tag (and parent) if neccesary. If false, then delete tag.
(I have no other way of referring to the tag I need (since I have layers on layers of functions to automate this process on a large scale, you can check out my previous question here Python Lxml: Adding and deleting tags)).
Edit edit: Another issue:
I don't have a variable containing the parent of the element to add, just a variable containing the <asset>
object. I am trying to get the parent of the node I want using the xpath and a variable pointing to the ` tag.
Edit edit edit: Never mind the above, I will fix the issue by shorting the xpath to point to the parent, and using a variable name to refer to each item.
Although I'm not sure that combining add & remove functionality in 1 function is good idea, but anyway this is likely to work as you're expecting.