1

我在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 文档(参数“xmlResponseBody”)中搜索一个属性(参数“attribute”)。我想使用 XPath 来解决这个任务。在代码中,我用“// something wrong”注释,变量节点为空。我应该怎么办?我的代码有什么错误?

谢谢 !马尔维夫

4

1 回答 1

2

如果没有看到示例 xml(或其中的一部分),很难回答这个问题,但您可以使用

xpath.compile("//@" + attribute)

这意味着在上下文节点及其后代中搜索名为属性的属性。您可以在此处获得更多信息。

于 2013-07-10T14:53:34.450 回答