How to handle adding elements and their parents using xpath

Ok, I have a case where I need to add a tag to a specific other tag specified in xpath.

Xml example:

<?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 the <missions> to both assets. However, the second asset is missing the parent <services> tag that I want to add. Each asset tag is stored in a variable (e.g. node1, node2).

I have the following xpath: xpath1 = services/missions , which due to the way my program works, I can’t just store in another form (i.e. I don’t have space to store only services )

I need to check and check if the mission tag exists, and if so, do nothing. If the tag does not exist, I need to create it. If its parent does not exist, I also need to create it.

How to do this simply using the xpath string?

Edit: I want to create all this by a boolean value: i.e. val = true, and then create the tag (and parent) if necessary. If false, remove the tag.

(I have no other way to refer to the tag that I need (since I have layers on function layers to automate this process on a large scale, you can check my previous question here Python Lxml: adding and removing tags )).

Edit edit: Another issue:

I do not have a variable containing the parent of the element to be added, only a variable containing the <asset> object. I am trying to get the parent element of node, I want to use xpath and a variable pointing to a tag.

Editing editing: do not pay attention to the above, I will fix the problem by encoding xpath to indicate the parent, and using the variable name to refer to each element.

+4
source share
1 answer
 def to_xml(parent, xpath, value): """ parent: lxml.etree.Element xpath: string like 'x/y/z', anything more complex is likely to break value: anything, if is False - means delete node """ # find the node to proceed further 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 # do whatever is specified vy value if value is False: node.getparent().remove(node) else: node.text = str(value) 

Although I'm not sure that combining add and remove functions into 1 function is a good idea, but in any case, this will most likely work the way you expect.

+2
source

Source: https://habr.com/ru/post/1346663/


All Articles