如何使用Java获取XML中的节点?

时间:2015-07-21 10:07:17

标签: java xml

我想获取节点ServerVersion

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

我试过了:

@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);
}

但我不确定如何获取节点的ID。

有没有更简单的方法?甚至字符串解析就足够了?

1 个答案:

答案 0 :(得分:0)

xml元素Id中没有定义属性SERVER_VERSION。您可以使用document.getElementByTagName("SERVER_VERSION")来获取值。

或使用XPath读取节点:

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);