使用java和XPath搜索xml文档中的属性
我在java中有以下方法:使用java和XPath搜索xml文档中的属性,java,xml,Java,Xml,我在java中有以下方法: private static String getAttributValue(String attribute, String xmlResponseBody) { String searchAttributeValue = ""; try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); Documen
private static String getAttributValue(String attribute, String xmlResponseBody) {
String searchAttributeValue = "";
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlResponseBody)));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
try {
XPathExpression expr = xpath.compile("@" + attribute);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodeList = (NodeList) result;
Node node = nodeList.item(0); // something wrong??
searchAttributeValue = node.getTextContent();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
return searchAttributeValue;
}
我在xml文档(参数“XMLResponseBy”)中搜索属性(参数“attribute”)。我想使用XPath来解决这个任务。在代码中,我用“//something”注释错误,变量节点为null。我该怎么办?我的代码中有什么错误
谢谢!
Marwief如果不查看示例xml(或其中的一部分),很难回答这个问题,但是您可以使用
xpath.compile("//@" + attribute)
这意味着在上下文节点及其子节点中搜索名为attribute的属性。你可以得到更多的信息