java - How to parse an xml and get the content of specific element -


my xml string

got message 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> 

now have writtent function trying content of element messagecontent i.e <hi>k786</hi> getting null value always. function parse above xml is:

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 showing 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;     (int = 0; < nodes.getlength(); i++) {         system.out.println("the message obtained after parsing : "                 + nodes.item(i).getnodevalue());         resultmsg = nodes.item(i).getnodevalue();     }      return resultmsg; } 

what have done wrong in here? in advance

you need define name space uri first before selecting xpath. example, first define namespace uri follows on root;

element.setattribute("xmlns:ns1", "http://www.openoandm.org/xml/isbm/"); xpath.compile("//ns1:messagecontent"); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -