X-Fate
X-Fate

Reputation: 323

XML in Java: Get values from specific elements

I have a question concering the returning of values from deep within a xml structure. First, here's the xml-code:

<?xml version="1.0" encoding="UTF-8" ?> <log> <published>2014-03-28T15:28:36.646Z</published> <actor> <objectType>person</objectType> <id>e1b8948f-321e-78ca-d883-80500aae71b5</id> <displayName>anonymized</displayName> </actor> <verb>update</verb> <object> <objectType>concept</objectType> <id>a1ad6ace-c722-ffa9-f58e-b4169acdb4e3</id> <content>time</content> </object> <target> <objectType>conceptMap</objectType> <id>4b8f69e3-2914-3a1a-454e-f4c157734bd1</id> <displayName>my first concept map</displayName> </target> <generator> <objectType>application</objectType> <url>http://www.golabz.eu/content/go-lab-concept-mapper</url> <id>c9933ad6-dd4a-6f71-ce84-fb1676ea3aac</id> <displayName>ut.tools.conceptmapper</displayName> </generator> <provider> <objectType>ils</objectType> <url>http://graasp.epfl.ch/metawidget/1/b387b6f</url> <id>10548c30-72bd-0bb3-33d1-9c748266de45</id> <displayName>unnamed ils</displayName> </provider> </log>

I found a method here at Stackoverflow which deals with that (How to retrieve element value of XML using Java?):

protected String getString(String tagName, Element element) {
    NodeList list = element.getElementsByTagName(tagName);
    if (list != null && list.getLength() > 0) {
        NodeList subList = list.item(0).getChildNodes();

        if (subList != null && subList.getLength() > 0) {
            return subList.item(0).getNodeValue();
        }
    }

    return null;
}

My problem is that I don't know how to get a specific ID (or the value of an other element) with that method WITHOUT using explicit pre-defined methods (I want to pass the ID I look for in the method-head itself). If I use getString("id", document.getDocumentElement) it returns just the "e1b8948f-321e-78ca-d883-80500aae71b5"-ID. What to do if I want to get the ID "a1ad6ace-c722-ffa9-f58e-b4169acdb4e3" which is a subnode from <object>?

Upvotes: 2

Views: 1472

Answers (1)

M A
M A

Reputation: 72884

You can use an XPath expression for this.

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpression = xPath.compile("//object/id");

// this should return one "id" node
NodeList idNodelist = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
Node idNode = idNodelist.item(0);
System.out.println(idNode.getTextContent());

Upvotes: 1

Related Questions