Jason
Jason

Reputation: 371

XElement parsing from XDocument, far below, repeated 3

//      <sdl:seg id="1" conf="Translated">
//              <sdl:previous origin="source">
//                      <sdl:value key="created">Quick</sdl:value>
//                      <sdl:value key="modified">Brown</sdl:value></sdl:previous>
//              <sdl:value key="created">Fox</sdl:value>
//              <sdl:value key="modified">Jumps</sdl:value></sdl:seg>             

foreach (XElement x in myDoc.Descendants(ns + "seg"))           
    foreach (XElement y in myDoc.Descendants(ns + "value"))
        foreach (var z in y.Attributes())
            if (z.Value == "modified")      
                MessageBox.Show(y.Value);

I had "Brown" and "Jumps".

I want to have only "Jumps". (I mean only children not grandchild"s")

Help please.

At the moment, I'm studying only for "foreach" loops not LINQ (I know that is good one).

Regards.

[Edit] How about this. It emits nothing..

foreach (var x in d.Descendants("seg").Elements("value").Attributes().Some("modified")
    MessageBox.Show(x.Value);

[Edit 2]

foreach (var x in d.Descendants("seg").Elements("value").Attributes().Where(x => x.Value == "modified"))
MessageBox.Show( x.Parent.Value);

[Edit 3]

foreach (var x in d.Descendants("seg").Elements("value").Where(x => x.Attribute("key").Value == "modified"))
MessageBox.Show(x.Value);

Upvotes: 2

Views: 29

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Use Elements instead of Descendants.

foreach (XElement x in myDoc.Descendants(ns + "seg").Elements(ns + "value"))           
    foreach (var z in x.Attributes())
        if (z.Value == "modified")      
            MessageBox.Show(x.Value);

A shorter version:

foreach (XElement x in myDoc.Descendants(ns + "seg").Elements(ns + "value"))
    if (x.Attributes().Any(a => a.Value == "modified"))
        MessageBox.Show(x.Value);

Upvotes: 2

Related Questions