1

I have a fairly deeply nested xml structure and I would like to find an element with a particular value after I have already selected a node. In the sample below I have an array of 'B' and after selecting each of the 'B' nodes I would like to get the text of one of the children (which are not consistent) that starts with the word 'history'

<A> <Items> <B> <C> <D>history: pressed K,E</D> // could be nested anywhere </C> </B> <B> <C> <E>history: pressed W</E> </C> </B> </Items> </A> // Select the nodes from the array (B) var nodes = select(xmldoc, "//A/Items/B"); // Iterate through the nodes. nodes.forEach(node){ // is it possible to select any element that starts with the text 'history' from the already selected node. var history = select(node, "???[starts-with(.,'history')]"); 

all the samples I have seen start with : //*[text()] which searches from the root of the structure.

1 Answer 1

1
//B//*[starts-with(normalize-space(), 'history')] 

looks like it would do what you intend.

It selects "any descendant element of <B> whose text content starts with 'history'".

Manual iteration to find further nodes is not typically necessary. XPath does that for you. If you must iterate for some other reason, use the context node . to select.

nodes.forEach(function (node) { var history = select(node, "./*[starts-with(.,'history')]"); }); 

If you are actually looking for "any text node..."

//B//text()[starts-with(normalize-space(), 'history')] 

Or "any element node that has no further child elements..."

//B//*[not(*) and starts-with(normalize-space(), 'history')] 
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately this still returns 2 results and not the result of the selected node. It would be because we are starting at //B which has multiple records.
Something like this works: select(node, "C/*/[starts-with(normalize-space(.),'history')]"); so it will select from element <D> or <E>. The * searches all the children at the current level it doesn't search the children's children which makes sense. I was actually looking for a way to do a full search and all children from the current node.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.