How to handle adding elements and their parents us

2019-04-10 10:00发布

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.

1条回答
萌系小妹纸
2楼-- · 2019-04-10 10:02
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 & remove functionality in 1 function is good idea, but anyway this is likely to work as you're expecting.

查看更多
登录 后发表回答