XML看起来像这样:
<abc:employee>
<abc:name>SALARY</abc:name>
<abc:value>Yes</abc:value>
<abc:previousValue/>
<abc:qualification>
<abc:code>Basic</abc:code>
</abc:qualification>
</abc:employee>
需要搜索“SALARY”并获取下一个标记的值,即“是”
我该怎么做?尝试了XPath方式,代码如下:
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression xPathExpr = xpath.compile("//*[contains(., 'SALARY')]");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("emp.xml");
NodeList nl = (NodeList)xPathExpr.evaluate(doc.getFirstChild(), XPathConstants.NODESET);
System.out.println(nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
System.out.println(nl.item(i).getTextContent());
}
从Search for element value in an XML file得到一些想法 另外,我如何只获得元素值?在这种情况下只是 - '是'?
答案 0 :(得分:0)
您可以使用此XPath表达式来获取包含文本'SALARY'
的元素后面的最近元素:
//*[contains(., 'SALARY')]/following-sibling::*[1]
答案 1 :(得分:0)
使用以下xpath:
string(//*[.='SALARY']/following-sibling::*)
这个评估的xpath在你的xml上返回字符串Yes