【问题标题】:How to parse an xml and get the content of specific element如何解析 xml 并获取特定元素的内容
【发布时间】:2013-04-18 05:41:52
【问题描述】:

我的 xml 字符串是

Got message from Queue ==> <?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003
/05/soap-envelope"><soapenv:Body><ns1:PostPublicationResponse xmlns:ns1="http://www.openoandm.org/xml/ISBM/"><ns1:Messag
eID>urn:uuid:7d361fb0-bc54-48bd-bbd1-6e34960ef3f8</ns1:MessageID><ns1:MessageContent><MessageContent xmlns="http://www.o
penoandm.org/xml/ISBM/"><hi>k786</hi></MessageContent></ns1:MessageContent></ns1:PostPublicationResponse></soapenv:Body>
</soapenv:Envelope>

现在我已经编写了一个函数,它试图获取 元素 MessageContent 的内容,即 &lt;hi&gt;k786&lt;/hi&gt;,但我总是得到空值。 我解析上述 xml 的函数是:

private String parseQueueMessage(String message)
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException {
    String resultMsg = "";
    DocumentBuilderFactory domFactory = DocumentBuilderFactory
            .newInstance();
    domFactory.setNamespaceAware(true);

    DocumentBuilder builder = domFactory.newDocumentBuilder();

    Document doc = builder.parse(new InputSource(new java.io.StringReader(
            message)));

    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value

    xpath.setNamespaceContext(new NamespaceContext() {

        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(String arg0) {
            return null;
        }

        @Override
        public String getPrefix(String arg0) {
            return null;
        }

        @Override
        public String getNamespaceURI(String arg0) {
            if("xmlns:ns1".equals(arg0)) {
                return "http://www.openoandm.org/xml/ISBM/";
            }
            return null;
        }
    });


    XPathExpression expr = xpath.compile("//xmlns:ns1:MessageContent");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("The message obtained after parsing : "
                + nodes.item(i).getNodeValue());
        resultMsg = nodes.item(i).getNodeValue();
    }

    return resultMsg;
}

我在这里做错了什么? 提前致谢

【问题讨论】:

    标签: java xpath xml-parsing


    【解决方案1】:

    在从 XPATH 中选择之前,您需要先定义名称空间 URI。例如,首先在根上定义命名空间URI如下;

    element.setAttribute("xmlns:ns1", "http://www.openoandm.org/xml/ISBM/");
    xpath.compile("//ns1:MessageContent");
    

    【讨论】:

    • 我已经更改了上面的代码并实现了命名空间,但是当我调用 nodes.item(i).getNodeValue(); 时它仍然给我 null;
    • 您不需要 xpath 表达式中的 xmlns 部分。只需使用 ns1 属性
    • 我还有一个疑问。假设我想提取 ns1:MessageID 以及 ns1:MessageContent。那么我应该如何编写我的代码,以便我可以同时获得两个值?
    • 你可以试试 xpath.compile("//ns1:MessageID|//ns1:MessageContent");
    【解决方案2】:

    //尝试类似...

    XmlDocument doc = new XmlDocument(); doc.LoadXml("urn:uuid:7d361fb0-bc54-48bd-bbd1-6e34960ef3f8k786 ");

    XmlElement elem = (XmlElement) doc.DocumentElement.FirstChild;
    Console.Write("{0}:{1} = {2}", elem.Prefix, elem.LocalName, elem.InnerText);
    Console.WriteLine("\t namespaceURI=" + elem.NamespaceURI);
    

    【讨论】:

      猜你喜欢
      • 2012-12-30
      • 2014-10-26
      • 1970-01-01
      • 2022-01-04
      • 2012-03-03
      • 2011-04-05
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多