c# - Read XML by its tag name -
i have xml services respond , here's sample :
<?xml version="1.0"?> <s:envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:body> <ns4:loginresponse xmlns="http://www.website.com/inctypes" xmlns:ns2="http://yyy.website.com/security" xmlns:ns3="http://yyy.incognito.com/service" xmlns:ns4="http:/yyy.website.com/wsdl/security"> <ns2:errorcode> <haserror>true</haserror> <status>status_error</status> <problemcode>-1</problemcode> <problemmessage>service provider not known</problemmessage> <extendedinformation>service provider not known</extendedinformation> </ns2:errorcode> </ns4:loginresponse> </s:body> </s:envelope>
i want value of tag
<haserror>true</haserror> <status>status_error</status> <problemcode>-1</problemcode> <problemmessage>service provider
and here's c# code:
foreach (xmlnode node in loginresp.documentelement) { if (node.firstchild.firstchild.haschildnodes == true) { foreach (xmlnode y in node.firstchild.firstchild.childnodes) { haserror = y.innerxml; status= y.innerxml; } } }
but gives me either haserror
, errocode
same value of <ns2:errorcode>
<extendedinformation>service provider not known</extendedinformation>
how <haserror>true</haserror>
<status>status_error</status>
value ?
you can try use linq-to-xml suggested @nomad17. makes not trivial is, xml has namespaces. hence need define xnamespace
s used match element names :
xnamespace ns = "http://www.website.com/inctypes"; xnamespace ns2 = "http://yyy.website.com/security"; var loginresp = xdocument.parse("xml string here"); //get <ns2:errorcode> element var errorcode = loginresp.descendants(ns2 + "errorcode").firstordefault(); if(errorcode != null) { //get <haserror> element under <ns2:errorcode> var haserror = (string)errorcode.element(ns + "haserror"); //get <status> element under <ns2:errorcode> var status = (string)errorcode.element(ns + "status"); }
Comments
Post a Comment