Reputation:
I have the following xml package that I can't seem to query since it doesn't contain a root element. Unfortunately, the xml payload can't be changed, so I'm stuck w/ this approach. I'm wondering if there's good way to do this with changes to my example. I tried using DesendantsAndSelf as well, but couldn't make it work. Tnx for your help.
string xml = @"<book number='3'>
<description>Test</description>
<chapter number='3-1-1'>
<description>Test</description>
</chapter>
<chapter number='3-1-2'>
<description>Test</description>
</chapter>
</book>";
Here's my code example:
XElement element= XElement.Parse(xml);
List<Book> books = ( from t in element.Descendants("book")
select new Book
{
number = (String)t.Attribute("number"),
description = (String)t.Element("description").Value,
// Load the chapter information
chapters = t.Elements("chapter")
.Select(te => new Chapter
{
number = (String)te.Attribute("number"),
description = (String)t.Element("description").Value
}).ToList(),
}).ToList();
foreach(var d in books)
{
Console.WriteLine(String.Format("number = {0}: description = {1}",d.number,d.description));
foreach(var c in d.chapters)
Console.WriteLine(String.Format("number = {0}: description = {1}",c.number,c.description));
}
This is my class object:
public class Book
{
public String number { get; set; }
public String description { get; set; }
public List<Chapter> chapters { get; set; }
}
public class Chapter
{
public String number { get; set; }
public String description { get; set; }
}
Upvotes: 1
Views: 976
Reputation: 56162
Simply change XElement element= XElement.Parse(xml);
to var element = XDocument.Parse(xml);
. In this case you will get a XDocument
instance, which has a book
descendant. If you use XElement element= XElement.Parse(xml);
you current element would be book
which doesn't have any book
descendants.
Upvotes: 1