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; }
}
bookis your root element. If you have multiplebookelements in one string just wrap it in a dummy element (e.g."<root>" + xml + "</root>";elementin this case is thebookelement. It has no decendants of typebook.