2012-11-18 51 views
3

我想使用Xdocument在Windows Store應用程序中解析xml。使用Xdocument進行簡單的Xml解析

我想這一點,但空返回:

XDocument xDoc; 
string title= ""; 

xDoc = XDocument.Load(url); 

var elements = from x in xDoc.Descendants() 
       select new 
       { 
        title = x.Descendants("title").First().Value, 
       }; 

foreach (var el in elements) 
    _title = title; 

的Xml內容:

<title type='text'>tiitle</title> 
<content type='text'> gfgdgdggd</content> 
<link rel='related' type='application/atom+xml' href='http....'/> 

如何能夠爲retrive從屬性的文本?

+0

請說明 - 你想要'title'元素的值還是'type'屬性的值。 –

+0

您的XML無效。你需要有一個根元素。 –

回答

3

正如ZevSpitz已經提到的,你的XML是無效的。我修改了一點,能夠測試我的代碼:

<root> 
    <title type="text">title</title> 
    <content type="text">gfgdgdggd</content> 
</root> 

可以檢索與下面的代碼從type屬性值:如下

XDocument xDoc = XDocument.Parse(xml); 

var types = 
    from x in xDoc.Root.Descendants() 
    select x.Attribute("type").Value; 

在我的情況xml聲明:

private string xml = 
    @"<root> 
     <title type=""text"">title</title> 
     <content type=""text"">gfgdgdggd</content> 
    </root>"; 

如果文件內容相同,仍然可以使用代碼從URL加載XML。

+0

使用'Root'的好電話。我寧願不使用'.Value',而是將其轉換爲'string',因爲如果元素上沒有'type'屬性,則'Attribute'方法將返回'null',並調用'Value'屬性將導致一個'NullReferenceException'。如果轉換爲'string',返回的值將只是null,'string'類型可以容納。 –

+0

@ZevSpitz我想這取決於預期的XML結構,但我喜歡你的方法。我相信它會派上用場。在這種情況下,我通常使用'!= null'檢查。 –

+1

[如何檢索元素的值(LINQ to XML)](http://msdn.microsoft.com/zh-cn/library/bb387049%28v=VS.100%29.aspx)。 –

0

嘗試:

var types = 
    from e in xDoc.Descendants() 
    select (string)e.Attribute("type"); 

foreach (string type in types) { 
    Console.WriteLine(type); 
} 
+0

不工作,返回null – Evox

+0

是否爲所有元素返回'null'?或只爲其中之一? –