简体   繁体   中英

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 ?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM