从XDocument获取数据

3

这是我的XML文件:

<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中检索它并将其添加到Book类中,但是我无法获取日期。我想要检索友好的日期。

这是我的代码:

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 = 
                }
            );

如何获取友好的日期显示?

2个回答

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

我注意到你要求友好的日期,但我想如果你得到一个真正的DateTime值,你就可以随心所欲地处理它。 - Tergiver

0

我还没有测试过这个,但它应该看起来像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接