Get XElement from XDocument

I have XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...

I load xml into XDocument

XDocument xDoc = XDocument.Parse(xmlString);

and next i try to find XElement contains Body

I tried

XElement bodyElement = xDoc.Descendants(XName.Get("Body", "s")).FirstOrDefault();

or

XElement bodyElement = xDoc.Descendants("Body").FirstOrDefault();

or

XElement bodyElement = xDoc.Elements("Body").FirstOrDefault();

but bodyElement always is null.

If I try add namespace

XElement bodyElement = xDoc.Descendants("s:Body").FirstOrDefault();

I got an error about :.

If I remove s from XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...

Everything works.

How to get XElement containing Body?

Jon Skeet
people
quotationmark

You're trying to look in a namespace with a URI of "s" - it doesn't have that URI. The URI is "http://schemas.xmlsoap.org/soap/envelope/". I'd also suggest avoiding XName.Get and just using XNamespace and the XName +(XNamespace, string) operator:

XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/";
XElement body = xDoc.Descendants(s + "Body").FirstOrDefault();

people

See more on this question at Stackoverflow