简体   繁体   中英

c# XDocument issue

I am quite new to xml-parsing.

Following very basic tutorials I try to parse the following xml returned by a CalDav server:

<?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...

Any help would be much appreciated!

Your response element is actually in a namespace, due to this attribute in the root node:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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