views:

23

answers:

1

I'm always so excited to get a chance to use linq to xml and then I run into the same PITA issue with namespaces. Not sure what is wrong with me but I can never quite grok what is going on. Basically I just need to get the value of the responseCode element and so far I have had no luck :(

<?xml version="1.0" encoding="IBM437"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"&gt;
 <soapenv:Body>
   <ns1:ActionResponse xmlns:ns1="http://cbsv.ssa.gov/ws/datatype"&gt;
     <ns1:responseCode>0000</ns1:responseCode>
     <ns1:responseDescription>Successful</ns1:responseDescription>
   </ns1:ActionResponse>
 </soapenv:Body>
</soapenv:Envelope>
+2  A: 

Namespaces in LINQ to XML are really elegantly handled, IMO. Here's an example:

XNamespace ns1 = "http://cbsv.ssa.gov/ws/datatype";
XDocument doc = XDocument.Load(...);
string code = doc.Descendants(ns1 + "responseCode")
                 .Select(x => (string) x)
                 .First();

If you want to work down from the top, using both of the namespaces involved, that's okay too:

XNamespace ns1 = "http://cbsv.ssa.gov/ws/datatype";
XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
XDocument doc = XDocument.Load(...);
string code = (string) doc.RootElement
                          .Element(soapenv + "Body")
                          .Element(ns1 + "ActionResponse")
                          .Element(ns1 + "responseCode");

Just to be clear, there's nothing forcing you to use the same variable name as the namespace prefix in the XML - I've just done so for clarity.

Jon Skeet