Finding an XML Element anywhere in a document using Java

Given the following XML (example):

<?xml version="1.0" encoding="UTF-8"?> <rsb:VersionInfo xmlns:atom="http://www.w3.org/2005/Atom" xmlns:rsb="http://ws.rsb.de/v2"> <rsb:Variant>Windows</rsb:Variant> <rsb:Version>10</rsb:Version> </rsb:VersionInfo> 

I need to get the Variant and Version values. My current approach uses XPath as I cannot rely on this structure. All I know is that there is an rsb:Version element in the document.

 XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "//Variant"; InputSource inputSource = new InputSource("test.xml"); String result = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING); System.out.println(result); 

This, however, does not display anything. I tried the following XPath expressions:

  • // Option
  • // Variant / text ()
  • // RSB: Option
  • // RSB: Variant / text ()

What is the correct XPath expression? Or is there an even easier way to get to this element?

+5
source share
1 answer

I would suggest just scrolling through the document to find the given tag

 public static void main(String[] args) throws SAXException, IOException,ParserConfigurationException, TransformerException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new File("test.xml")); NodeList nodeList = document.getElementsByTagName("rsb:VersionInfo"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // do something with the current element System.out.println(node.getNodeName()); } } } 

Edit: Yasin has indicated that he will not receive child nodes. This should point you in the right direction for getting children.

 private static List<Node> getChildren(Node n) { List<Node> children = asList(n.getChildNodes()); Iterator<Node> it = children.iterator(); while (it.hasNext()) if (it.next().getNodeType() != Node.ELEMENT_NODE) it.remove(); return children; } 
+3
source

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


All Articles