0

我的 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 的内容,即<hi>k786</hi>,但我总是得到空值。我解析上述 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;
}

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

4

2 回答 2

1

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

element.setAttribute("xmlns:ns1", "http://www.openoandm.org/xml/ISBM/");
xpath.compile("//ns1:MessageContent");
于 2013-04-18T06:05:24.217 回答
0

//尝试类似...

XmlDocument 文档 = 新 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);
于 2013-04-18T12:59:12.030 回答