2013-08-22 33 views
1

我試圖解析XML,這是在這個urlXDocument表示根級別的數據無效?

try 
{ 
    var xDoc = XDocument.Parse(requestedURL); 
    Response.Write("asd: " + xDoc.Descendants("entry").Count()); 
} 
catch (Exception err) 
{ 
    Response.Write(err.Message); 
} 

,但它與Data at the root level is invalid. Line 1, position 1.

我在哪裏錯了回覆?

回答

2

您應該使用XDocument.Load而不是XDocument.Parse。那是因爲XDocument.Parse希望在您嘗試從URL加載它時收到一個XML字符串。

編輯

也有XML命名空間的問題。試試這個

var xDoc = XDocument.Load(requestedURL); 
XNamespace ns = "http://www.w3.org/2005/Atom"; 
var count = xDoc.Descendants(ns + "entry").Count(); 

http://msdn.microsoft.com/en-us/library/bb343181.aspx

+0

已經做到這一點,但'xDoc.Descendants( 「入口」)。COUNT()'說0,這是不是0,所以我想負荷不解析XML? – markzzz

+0

@markzzz我更新了答案 – I4V

+0

爲什麼我需要指定命名空間來提取這些數據?我第一次看到它... – markzzz

0

試試這個。

try 
{ 
    var xDoc = XDocument.Load(requestedURL); 
    Response.Write("asd: " + xDoc.Descendants("entry").Count()); 
} 
catch (Exception err) 
{ 
    Response.Write(err.Message); 
} 
+0

是的,試過了。但它說入口有0個項目?他們是11 ... – markzzz

相關問題