Java XML获取特定属性上节点的值

Java XML获取特定属性上节点的值,java,xml,xml-parsing,Java,Xml,Xml Parsing,我知道这有很多链接,但我找不到解决方案。根据我的搜索,我得出了一些代码: DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Doc

我知道这有很多链接,但我找不到解决方案。根据我的搜索,我得出了一些代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));

Document doc = builder.parse(is);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();

XPathExpression expr = xpath.compile("//Field[@Name=\"id\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println(nl.getLength());
for(int i=0;i<nl.getLength();i++){
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("Name").getNodeValue();
    System.out.println(key);
}
DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
InputSource is=新的InputSource();
is.setCharacterStream(新的StringReader(xml));
文档doc=builder.parse(is);
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“//字段[@Name=\'id\']”);
NodeList nl=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
System.out.println(nl.getLength());

对于(int i=0;i您的代码将获取name属性等于“Id”的字段节点。您可以更改XPath表达式以获取name属性为“Id”的元素的Value节点内的元素文本。因此XPath表达式应为:

//Field[@Name=\"id\"]/Value/text()
然后将for循环中的代码更改为

        Node currentItem = nl.item(i);
        System.out.println(currentItem.getNodeValue());

此XPath将找到正确的Value元素:
//Field[@Name=“id”]/Value


还可以通过表达式
字符串(//Field[@Name=“id”]/Value)获取XPath以返回元素的连接文本内容
,这可能是最简单的方法。请注意,在本例中,您应该直接从
expr.evaluate
获取字符串,而不是节点列表。

请注意,您必须自己使用这种方法来处理连接多个文本节点的问题。通常,使用
字符串让XPath引擎为您执行此操作更简单(…)
函数。
        Node currentItem = nl.item(i);
        System.out.println(currentItem.getNodeValue());