2013-04-18 2 views
0

Мой XML СтрокаКак разобрать 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> 

Теперь я writtent функцию, которая пытается получить Содержание элемента 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; 
} 

Что я сделал неправильно здесь? Заранее спасибо

ответ

1

Перед выбором из XPATH необходимо определить URI пространства имен. Например, сначала определите URI пространства имен, как показано ниже в корне;

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

Я изменил свой код выше и реализовал пространство имен, но все же он дает мне null, когда я вызываю node.item (i) .getNodeValue(); – Roy

+0

вам не нужна часть xmlns в выражении xpath. просто используйте атрибут ns1 – dinukadev

+0

еще один запрос, который у меня есть. Предположим, я хочу извлечь ns1: MessageID, а также ns1: MessageContent. то как мне написать свой код, чтобы я мог одновременно получать оба значения? – Roy

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); 
Смежные вопросы