2010-05-26 27 views
3
獲取數據

因此,這裏是我的XML文件:從的XDocument

<book> 
    <title>Book Title</title> 
    <author>Book Author</author> 
    <pubDates> 
     <date format="standard">1991-01-15</date> 
     <date format="friendly">January 1991</date> 
    </pubDates> 
</book> 

我將數據裝入一個XDocument,然後從檢索的XDocument它並將其添加成書類,但我有麻煩取得日期。我想檢索友好的日期。

這是我有:

XDocument xml = XDocument.Load("http://www.mysite.com/file.xml"); 

List<Book> books = new List<Book>(); 
books.Add(new Book 
       { 
        Title = xml.Root.Element("title").Value, 
        Author = xml.Root.Element("author").Value, 
        //PubDate = 
       } 
      ); 

我怎樣才能得到友好的日期?

回答

5
PubDate = DateTime.ParseExact(xml.Root.Elements("pubDates") 
.Elements("date") 
.Where(n => n.Attribute("format").Value == "standard") 
.FirstOrDefault() 
.Value 
, "yyyy-mm-dd", CultureInfo.InvariantCulture); 
+0

這工作太好了,謝謝。 – Steven 2010-05-26 22:54:03

+0

我注意到你問的友好日期,但我想如果你得到一個真正的日期時間值,你可以做任何你想要的東西。 – Tergiver 2010-05-27 00:37:32

0

我沒有測試過這一點,但它應該是這個樣子:

from node in xml.DescendantNodes("pubDates").DescendantNodes("date") 
where node.Attribute("format").Value == "friendly" 
select node.Value.FirstOrDefault()