简体   繁体   中英

How to fetch node in XML using Java?

I want to fetch value of the node ServerVersion

<result>
<response id="27mSTG">
<routing>
<configs>
<linqmap.routing.RoutingServerConfig>
<SERVER_VERSION>1.0.388</SERVER_VERSION>
<PRE_PROCESSING_FILE_LOCATION/>

I have tried:

@Override
public void getProp(String prop) {
    try {
        final Document document = loadXMLFromString();
        document.getElementById(??);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Document loadXMLFromString() throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xmlString));
    return builder.parse(is);
}

But I'm not sure how to get the node's ID.

Is there any easier way? Maybe even string parsing is enough?

There is no attribute Id defined in your xml element SERVER_VERSION . You can use document.getElementByTagName("SERVER_VERSION") to get the value.

Or use XPath to read the node:

final Document document = loadXMLFromString();
 XPathFactory xpathfactory = XPathFactory.newInstance();
 XPath xpath = xpathfactory.newXPath();
 String xpathExpr="/result/SERVER_VERSION"; // assume result is the root node.
 Node node=(Node)xPath.compile(xpathExpr).evaluate(document, XPathConstants.NODE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM