简体   繁体   English

C#XDocument问题

[英]c# XDocument issue

I am quite new to xml-parsing. 我是xml解析的新手。

Following very basic tutorials I try to parse the following xml returned by a CalDav server: 遵循非常基础的教程,我尝试解析CalDav服务器返回的以下xml:

<?xml version="1.0" encoding="utf-8" ?>
<multistatus xmlns="DAV:">
 <response>
  <href>/caldav.php/icalendar.ics</href>
  <propstat>
   <prop>
    <getetag>"xxxx-xxxx-xxxx"</getetag>
   </prop>
   <status>HTTP/1.1 200 OK</status>
  </propstat>
 </response>
 <sync-token>data:,20</sync-token>
</multistatus>

Now I want to find my "response" descendants as follows: 现在,我想找到我的“响应”后代,如下所示:

Doc = XDocument.Parse(response);
foreach (var node in xDoc.Root.Descendants("response")) {
  // process node
}

No descendant is found. 找不到后代。 Am I missing something here? 我在这里想念什么吗? My root is indeed a "multistatus" element, it says it has elements, but it doesn't seem as they can be found by name... 我的根目录确实是一个“ multistatus”元素,它说它具有元素,但是似乎无法按名称找到它们。

Any help would be much appreciated! 任何帮助将非常感激!

Your response element is actually in a namespace, due to this attribute in the root node: 由于根节点中的以下属性,您的response元素实际上位于名称空间中:

xmlns="DAV:"

That sets the default namespace for that element and its descendants. 设置该元素及其后代的默认名称空间。

So you need to search for elements in that namespace too. 因此,您还需要在该命名空间中搜索元素。 Fortunately, LINQ to XML makes that really simple: 幸运的是,LINQ to XML使事情变得非常简单:

XNamespace ns = "DAV:";
foreach (var node in xDoc.Root.Descendants(ns + "response"))
{
    ...
}

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

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