简体   繁体   English

使用Java和XPath在xml文档中搜索属性

[英]Search a attribute in a xml document with java and XPath

i have the following method in java: 我在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;
}

I search an attribute (parameter "attribute") in a xml document (parameter "xmlResponseBody"). 我在xml文档(参数“ xmlResponseBody”)中搜索属性(参数“ attribute”)。 I would like to use XPath to solve this task. 我想使用XPath解决此任务。 At the code, which i have comment with "// something wrong", the variable node is null. 在代码中,我用“ //出了点问题”注释,变量节点为空。 What should i do? 我该怎么办? What is the mistake in my code? 我的代码有什么错误?

Thanks ! 谢谢 ! Marwief Marwief

It is hard to answer this without seeing the sample xml(or part of it), but you can search for an attribute using 如果不查看示例xml(或其中的一部分),很难回答这个问题,但是您可以使用来搜索属性

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

It means search for attribute named attribute inside context node and its descendants. 这意味着在上下文节点及其后代中搜索名为attribute的属性 You can get more information here . 您可以在此处获得更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM