2015-06-12 23 views
1

我對xml解析相當陌生。c#XDocument問題

繼非常基本教程我嘗試解析由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 
} 

沒有後代被發現。我在這裏錯過了什麼嗎?我的根的確是一個「多狀態」元素,它說,它具有的元素,但它似乎並沒有因爲他們可以通過名字找到...

任何幫助,將不勝感激!

+1

LINQ到XML是非常強大的,簡單易學,這將是值得的退後一步,也更多地瞭解XPath和甚至XSLT - 如果只更多地欣賞linq-to-xml。 – NicoE

回答

4

response元素實際上是在一個命名空間,由於根節點這個屬性:

xmlns="DAV:" 

那臺默認命名空間爲元素和它的後代。

因此,您還需要搜索該名稱空間中的元素。幸運的是,LINQ到XML使真正簡單:

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

感謝您的即時回答! – neggenbe

+0

這也適用:xDoc.Root.Descendants()。其中​​(x => x.Name.LocalName ==「response」) – jdweng

+0

@jdweng:是的,但它不像IMO那樣乾淨。 –