简体   繁体   中英

How to read data from xml file using linq to xml?

Trying to read this xml using Linq to XML

<Root>
    <shelves>
        <bookNumber>12</bookNumber>
        <coverType unit="H">soft</coverType>
        <pages>100</pages>
        <Weight units="lb">1.2</Weight>
        <chapter sample="1">example 1</<chapter>
        <chapter sample="2">example 2</<chapter>
        <chapter sample="3">example 3</<chapter>
        <chapter sample="4">example 4</<chapter>
        <chapter sample="5">example 5</<chapter>
        <chapter sample="6">example 6</<chapter>
        <chapter sample="7">example 7</<chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        <chapter .................</chapter>
        ..............
    </shelves>
</Root>

Thats the code i am trying with:-. But How will read values all the elements 'Chapter'?

var book = from b in xml.Root.Elements("shelves")
                             select b;
    foreach (var s in book)
    {
        booknumber = s.Element("bookNumber").Value,
        covertype = s.Element("bookNumber").Value,
        coverTypeUnit = s.Element("bookNumber").Attribute("unit").Value,
        ...........
        chapter = s.Element("bookNumber").Value ????
    }

You may find these links usefull:

linq-to-read-xml

101 LINQ Samples

var values = s.Elements("chapter").Select(n => n.Value).ToArray();

Furthermore, you're reading from the same element (booknumber) over and over. You might want to check your code.

EDIT: to also yield the attribute:

s.Elements("chapter").
Select(n => new {Topic = n.Attribute("topic").Value, Value = n.Value}).
ToArray();

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