Get XML nodes from a specific tree level

I need a method like Document.getElementsByTagName (), but one that only searches for tags from a certain level (i.e. not nested tags with the same name)

Example file:

<script> <something> <findme></findme><!-- DO NOT FIND THIS TAG --> </something> <findme></findme><!-- FIND THIS TAG --> </script> 

Document.getElementsByTagName () simply returns all the findme tags in the document.

+4
source share
3 answers

Here is an example with XPath

 import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class TestXPath { private static final String FILE = "a.xml" ; private static final String XPATH = "/script/findme"; public static void main(String[] args) { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder builder; try { builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(FILE); XPathExpression expr = XPathFactory.newInstance().newXPath().compile(XPATH); Object hits = expr.evaluate(doc, XPathConstants.NODESET ) ; if ( hits instanceof NodeList ) { NodeList list = (NodeList) hits ; for (int i = 0; i < list.getLength(); i++ ) { System.out.println( list.item(i).getTextContent() ); } } } catch (Exception e) { e.printStackTrace(); } } } 

WITH

 <script> <something> <findme>1</findme><!-- DO NOT FIND THIS TAG --> </something> <findme>Find this</findme><!-- FIND THIS TAG --> <findme>More of this</findme><!-- FIND THIS TAG AS WELL --> </script> 

This gives

 Find this More of this 
+5
source

If you use the DOM, the only way I can think of is through a recursive function that looks at the children of each element.

+1
source

Application:

 /*/findme 

This XPath expression selects all findme elements that are children of the top element of the XML document.

This expression :

 //findme[count(ancestor::*) = 5] 

selects all findme elements in an XML document that have exactly five ancestral elements - that is, they are all at level 6.

0
source

Source: https://habr.com/ru/post/1342162/


All Articles