OrElse
OrElse

Reputation: 9989

Another Simple LINQ to XML query

This one is my XML

 Dim X = <BODY>
   <HEAD1>
    <Eyes>BLUE</Eyes>
   </HEAD1>
   <HEAD2>
    <Eyes>BROWN</Eyes>
   </HEAD2>
   </BODY>

Until now i managed to get the HEAD parts. Now how can i iterate within the HEAD parts?

 Dim HEADS = From element In X.Elements Select element.Name.LocalName
 For Each c In HEADS
   Dim Local As String = c
   Dim COLORSofEYES = SELECT child nodes WHERE c 'Something like that i guess
 Next

The above should return on first iterattion <Eyes>BLUE</Eyes> as ElementNodeType and on the second <Eyes>BROWN</Eyes>

Upvotes: 0

Views: 152

Answers (4)

anishMarokey
anishMarokey

Reputation: 11397

you can write it in a single LINQ query

in C#

IEnumerable<XElement> de = from p in xmlTree.Elements().Elements() 
                            select p;

output

<Eyes>BLUE</Eyes>

<Eyes>BROWN</Eyes>

Hope i got your question properly.

Note: in your case you can use Descendants also

Descendants: yield entire child and sub-tree
Elements   :  yield through only through your child

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134601

That's an odd format. I'm not sure what exactly you want to iterate over. If you just want to iterate over all <Eyes>, you could just do this:

Dim query = X...<Eyes>

Otherwise if you just want to get all the children of each <HEAD...>, you could do this:

Dim query = X.Elements.SelectMany(Function(e) e.Elements)

Or with XPath:

Dim query = X.XPathSelectElements("/*/*")

Upvotes: 0

OrElse
OrElse

Reputation: 9989

Found it!

Dim COLORSofEYES = From d In X.Descendants(Local).Descendants Select d

Upvotes: 0

grzeg
grzeg

Reputation: 368

The following code (in C#):

        var x = XElement.Parse(
            @"<BODY>    
              <HEAD1>     <Eyes>BLUE</Eyes>    </HEAD1>    
              <HEAD2>     <Eyes>BROWN</Eyes>    </HEAD2>    </BODY>");

        foreach(var head in x.Elements())
        {
            Console.WriteLine("head: {0}, eyes' colour: {1}", head.Name.LocalName, head.Element("Eyes").Value);
        }

will produce the following output:

head: HEAD1, eyes' colour: BLUE
head: HEAD2, eyes' colour: BROWN

Which I understand is what you want.

Upvotes: 1

Related Questions