phill.tomlinson
phill.tomlinson

Reputation: 1086

How to build up xpath expressions based on an XML node

I'm trying to solve the problem where there is a an xml node where I do not know the contents in advance, however I would like to construct all relevant xpaths to every leaf element. For example:

<parent>
  <child1>
    <subchild1></subchild1>
  </child1>
  <child2>
    <subchild2></subchild2>
  </child2>
</parent>

The code would then pull out the relevant xpaths for every leaf node, in this case the subchilds:

/parent/child1/subchild1
/parent/child2/subchild2

I've looked for any library support and have not found anything. Does anyone have a solution for this?

Upvotes: 0

Views: 141

Answers (1)

dpeacock
dpeacock

Reputation: 2747

Here is a solution I hacked together in groovy:

def xml = new XmlSlurper().parseText("""<parent><child1><subchild1></subchild1></child1><child2><subchild2></subchild2></child2></parent>""")

def buildXPathFromParents = {
    if (it.parent().is(it)) {"/" + it.name() } // If we are our own parent, then we are the highest node, so return our name.
    else {call(it.parent())+ "/" + it.name() } // if we have a parent node, append our path to its path.
}

def endNodes = xml.depthFirst().findAll{!it.childNodes()} // find all nodes which dont have any children
def xPaths = endNodes.collect{buildXPathFromParents(it)}

print xPaths

Groovy4lyf

Upvotes: 1

Related Questions