简体   繁体   中英

Parse xml elements with no root element using Linq in .Net

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM