Skip to main content
 首页 » 编程设计

c# XDocument问题

2024年02月06日15lvdongjie

我对 xml 解析很陌生。

按照非常基础的教程,我尝试解析 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> 

现在我想按如下方式找到我的“响应”后代:

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

未找到后代。我在这里错过了什么吗?我的root确实是一个“multistatus”元素,它说它有元素,但它似乎没有,因为它们可以通过名称找到......

如有任何帮助,我们将不胜感激!

请您参考如下方法:

您的 response 元素实际上位于命名空间中,因为根节点中有此属性:

xmlns="DAV:" 

为该元素及其后代设置默认命名空间。

因此您还需要在该命名空间中搜索元素。幸运的是,LINQ to XML 使这变得非常简单:

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