从 XDocument 获取 XElement
Get XElement from XDocument
我有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">
...
我将 xml 加载到 XDocument
XDocument xDoc = XDocument.Parse(xmlString);
然后我尝试找到 XElement
包含 Body
我试过了
XElement bodyElement = xDoc.Descendants(XName.Get("Body", "s")).FirstOrDefault();
或
XElement bodyElement = xDoc.Descendants("Body").FirstOrDefault();
或
XElement bodyElement = xDoc.Elements("Body").FirstOrDefault();
但 bodyElement
始终是 null
。
如果我尝试添加命名空间
XElement bodyElement = xDoc.Descendants("s:Body").FirstOrDefault();
我收到关于 :
的错误。
如果我从 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">
...
一切正常。
如何获取包含正文的XElement
?
您正在尝试查找 URI 为 "s" 的名称空间 - 它没有该 URI。 URI 是 "http://schemas.xmlsoap.org/soap/envelope/"
。我还建议避免使用 XName.Get
并仅使用 XNamespace
和 XName +(XNamespace, string)
运算符:
XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/";
XElement body = xDoc.Descendants(s + "Body").FirstOrDefault();
我有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">
...
我将 xml 加载到 XDocument
XDocument xDoc = XDocument.Parse(xmlString);
然后我尝试找到 XElement
包含 Body
我试过了
XElement bodyElement = xDoc.Descendants(XName.Get("Body", "s")).FirstOrDefault();
或
XElement bodyElement = xDoc.Descendants("Body").FirstOrDefault();
或
XElement bodyElement = xDoc.Elements("Body").FirstOrDefault();
但 bodyElement
始终是 null
。
如果我尝试添加命名空间
XElement bodyElement = xDoc.Descendants("s:Body").FirstOrDefault();
我收到关于 :
的错误。
如果我从 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">
...
一切正常。
如何获取包含正文的XElement
?
您正在尝试查找 URI 为 "s" 的名称空间 - 它没有该 URI。 URI 是 "http://schemas.xmlsoap.org/soap/envelope/"
。我还建议避免使用 XName.Get
并仅使用 XNamespace
和 XName +(XNamespace, string)
运算符:
XNamespace s = "http://schemas.xmlsoap.org/soap/envelope/";
XElement body = xDoc.Descendants(s + "Body").FirstOrDefault();