我在java中有以下方法:
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文档中搜索属性(参数“attribute”)(参数“xmlResponseBody”)。我想用XPath来解决这个任务。在我用“// something something”评论的代码中,变量节点为空。我该怎么办?我的代码中有什么错误?
谢谢! Marwief
答案 0 :(得分:2)
如果没有看到示例xml(或其中的一部分),很难回答这个问题,但您可以使用
搜索属性xpath.compile("//@" + attribute)
这意味着在上下文节点及其后代中搜索名为 attribute 的属性。您可以获得更多信息here。