1

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 ????
    }
makc
  • 2,569
  • 1
  • 18
  • 28
user1327064
  • 4,187
  • 5
  • 20
  • 30

2 Answers2

2

You may find these links usefull:

linq-to-read-xml

101 LINQ Samples

Community
  • 1
  • 1
Gregor Primar
  • 6,759
  • 2
  • 33
  • 46
1
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();
e_ne
  • 8,340
  • 32
  • 43
  • Thanks. Say each element 'Chapter' has an attribute 'topic'. How will get attributes as well in Array? – user1327064 Dec 18 '12 at 16:11
  • You can use anonymous types. See my post for an example. – e_ne Dec 18 '12 at 16:12
  • I believe that your current problem spans a bit too much from the original question. Please make another question or refer to documentation or a tutorial to solve it. – e_ne Dec 18 '12 at 16:33