Get data from XDocument

So here is my xml file:

<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>

I load the data into an XDocument and then extract it from the XDocument and add it to the Book class, but I can’t get the date. I would like to get a friendly date.

Here is what I have:

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

How can I get a friendly date?

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

I have not tested this, but it should look something like this:

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

Source: https://habr.com/ru/post/1747262/


All Articles