简体   繁体   English

从XDocument获取XElement

[英]Get XElement from XDocument

I have XML 我有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 我将xml载入XDocument

XDocument xDoc = XDocument.Parse(xmlString);

and next i try to find XElement contains Body 然后我尝试找到XElement包含主体

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 . 但是bodyElement始终为null

If I try add namespace 如果我尝试添加名称空间

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

I got an error about : . 我遇到一个错误:

If I remove s from XML 如果我从XML中删除s

<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 ? 如何获取包含Body的 XElement

You're trying to look in a namespace with a URI of "s" - it doesn't have that URI. 您正在尝试使用URI为“ s”的名称空间-它没有该URI。 The URI is "http://schemas.xmlsoap.org/soap/envelope/" . URI是"http://schemas.xmlsoap.org/soap/envelope/" I'd also suggest avoiding XName.Get and just using XNamespace and the XName +(XNamespace, string) operator: 我还建议避免使用XName.Get而只使用XNamespaceXName +(XNamespace, string)运算符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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