hello world hello world hello world

Xpath - How to select a node but not its child nodes

79 views Asked by At

I am trying to select a node but not any of its child nodes.

Example Input:

<Header attr1="Hello"> 
  <child1> hello </child1>
  <child2>world</child2>
</Header>

Expected Output: <Header attr1="Hello"> </Header>

Code:

Document xmlDoc = saxBuilder.build(inputStream);
Xpath x = XPath.newInstance("/Header");
eleMyElement = x.selectSingleNode(xmlDoc);
XMLOutputter output = new XMLOutputter();
output.outputString(eleMyElement) --> this is the output

I tried with /Header as XPath, it gives me the header along with child nodes.

2

There are 2 answers

2
Michael Kay On

You need to distinguish what is selected from what is displayed.

The XPath expression /Header selects one node only, the Header element. You say "it gives me", but what is "it"? Something is displaying the results of the XPath selection, and it is choosing to display the results by rendering the selected element with all its children. You need to look at the code that is displaying the result.

0
forty-two On

In this case you can simply do

eleMyElement.getContent().clear();

and all child nodes will be deleted.