简体   繁体   中英

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

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.

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.

In this case you can simply do

eleMyElement.getContent().clear();

and all child nodes will be deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM