如果元素具有xmlns属性,则XDocument和Linq返回null

Sri*_*ddy 22 c# xml linq-to-xml

有关XDocuments和Linq的新手,请建议一个从xml字符串中的特定标记中检索数据的解决方案:

如果我有一个来自webservice响应的XML字符串(为了方便我格式化了xml):

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetCashFlowReportResponse xmlns="http://tempuri.org/">
      <GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf>
    </GetCashFlowReportResponse>
  </soap:Body>
</soap:Envelope>
Run Code Online (Sandbox Code Playgroud)

使用以下代码,仅当GetCashFlowReportResponsetag没有"xmlns"属性时才能获取值.不知道为什么?否则,它始终返回null.

string inputString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetCashFlowReportResponse xmlns=\"http://tempuri.org/\"><GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf></GetCashFlowReportResponse></soap:Body></soap:Envelope>"    
XDocument xDoc = XDocument.Parse(inputString);
//XNamespace ns = "http://tempuri.org/";
XNamespace ns = XNamespace.Get("http://tempuri.org/");

var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
           select (string)c.Element("GetCashFlowReportPdf");

foreach (string val in data)
{
    Console.WriteLine(val);
}
Run Code Online (Sandbox Code Playgroud)

我无法更改Web服务以删除该属性.是否有更好的方法来读取响应并将实际数据返回给用户(以更易读的形式)?

编辑: 解决方案:

XDocument xDoc = XDocument.Parse(inputString);
XNamespace ns = "http://tempuri.org/";

var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
           select (string)c.Element(ns + "GetCashFlowReportPdf");
foreach (string val in data)
{
   Console.WriteLine(val);
}
Run Code Online (Sandbox Code Playgroud)

注意:即使所有子元素都没有namespace属性,如果你向元素添加"ns"代码也会有效,因为我猜孩子们从父级继承命名空间(参见SLaks的响应).

SLa*_*aks 15

您需要包含命名空间:

XNamespace ns = "http://tempuri.org/";

xDoc.Descendants(ns + "GetCashFlowReportResponse")
Run Code Online (Sandbox Code Playgroud)

  • @user:错了.默认名称空间(`xmlns ="..."`)由子元素继承. (2认同)