c# XDocument issue

115 views Asked by At

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!

1

There are 1 answers

8
Jon Skeet On BEST ANSWER

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"))
{
    ...
}