Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Document - How to get a tag's value by its name?

Tags:

java

dom

xml

I'm using Java's DOM parser to parse an XML file.

let's say I have the following XML

<?xml version="1.0"?>

<config>
    <dotcms>
        <endPoint>ip</endPoint>
    </dotcms>
</config>

</xml>

I like to get the value of 'endPoint'. I can do it with the following code snippet. (assuming that I already parsed it with DocumentBuilder)

NodeList nodeList = this.doc.getElementByTagName("dotcms");
Node nValue = (Node) nodeList.item(0);
return nValue.getNodeValue();

Is it possible to get a value of a field by a field's name? Like....

Node nValue = nodeList.getByName("endPoint") something like this...?

like image 671
Moon Avatar asked Sep 20 '11 19:09

Moon


1 Answers

You should use XPath for these sorts of tasks:

//endPoint/text()

or:

/config/dotcms/endPoint/text()

Of course Java has a built-in support for XPath:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//endPoint/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);
like image 185
Tomasz Nurkiewicz Avatar answered Sep 23 '22 15:09

Tomasz Nurkiewicz