开发者

How to handle adding elements and their parents using xpath

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>
  开发者_如何学Go <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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜