Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPATH select only first level children

Tags:

java

xml

xpath

I have the fowoling xml :

  <workflow URI=""> 
  <output ID="" URI="#out1"/>  
  <input ID="sessionToken" URI="#sessionToken"/>  
  <services> 
    <sequence> 
      <service URI=""> 
        <input ID="" URI=""/>  
        <input URI="" value=""/>  
        <output ID="" URI=""/> 
      </service> 
    </sequence> 
  </services> 
</workflow>

I want to select only the first level children of the workflow node and exclude from this selection the services node, so in my case I would only want

 <output ID="" URI="#out1"/>  
 <input ID="sessionToken" URI="#sessionToken"/>  

this two nodes selected, and I want to use XPATH in java for this. The additional requirments is that the selected node must have the URI parameter.

I have tried this :

XPathExpression expr = xpath.compile("//workflow[@URI='" + oldUrlValue.getNodeValue() + "'] | //workflow//*[not(local-name() = 'services') and @URI]");

but I get backall the nodes with URI parameters instead only the main workflow node and the first two children.

I have tried this

like image 327
simonC Avatar asked Oct 25 '25 16:10

simonC


2 Answers

It isn't clear what you mean by 'first level children' here, because services is located at the same level as output and input elements. If you mean to return direct child of workflow that do not have any further child element, then you can use the following XPath expression :

//workflow/*[not(*)]
like image 177
har07 Avatar answered Oct 27 '25 04:10

har07


Just use the astrik selector (*) to select children of the workflow node, then only select ones which contain the URI attribute ([@URI])

//workflow[@URI='" + oldUrlValue.getNodeValue() + "']/*[@URI]
like image 21
ug_ Avatar answered Oct 27 '25 06:10

ug_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!