Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locating XML element anywhere in the document with Java

Tags:

java

xml

xpath

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 values of Variant and Version. My current approach is using XPath as I cannnot rely on the given structure. All I know is that there is an element rsb:Version somewhere 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 output anything. I have tried the following XPath expressions:

  • //Variant
  • //Variant/text()
  • //rsb:Variant
  • //rsb:Variant/text()

What is the correct XPath expression? Or is there an even simpler way getting to this element?

like image 820
Robert Strauch Avatar asked Oct 18 '22 23:10

Robert Strauch


1 Answers

I would suggest just looping 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: Yassin pointed out that it won't get child nodes. This should point you in the right direction for getting the 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;
  }
like image 124
Michael Queue Avatar answered Oct 22 '22 08:10

Michael Queue