BAD_SEED
BAD_SEED

Reputation: 5056

How to correctly perform Linq-to-XML query?

I have a XDocument called currentIndex like that:

<INDEX>
   <SUBINDEX>
      <!-- Many tag and infos -->
   <SUBINDEX>
   <ITEM>
       <IDITEM>1</IDITEM>
   <ITEM>
   <ITEM>
       <IDITEM>2</IDITEM>
   <ITEM>
   ...
   <ITEM>
       <IDITEM>n</IDITEM>
   <ITEM>
</INDEX>

I would recreate a new XDocument similar to above one:

<INDEX>
   <SUBINDEX>
      <!-- Many tag and infos -->
   <SUBINDEX>
   <ITEM>
       <IDITEM>2</IDITEM>
   <ITEM>
</INDEX>

I want to do this in C#, I have tried starting in this way:

public void ParseItems(XDocument items)
{
    IEnumerable<XElement> items = from a in indexGenerale.Descendants(XName.Get("ITEM"))
                                  // where a.Element("IDITEM").Equals("2")
                                  select a;
    foreach(var item in items) {
        // do something
    }
}

Now the problem: If where clause is commented, items contains n elements (one for each ITEM tag), but if I remove that comments items is empty. Why this behaviour. How I need to perform a search?

Upvotes: 0

Views: 27

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101680

Use an explicit cast:

from a in indexGenerale.Descendants("ITEM")
where (string)a.Element("IDITEM") == "2"

a.Element("IDITEM") will return an XElement and it will never be equal to "2".Maybe you meant a.Element("IDITEM").Value.Equals("2"), that will also work but explicit cast is safer.It doesn't throw exception if the element wasn't found`,

Upvotes: 3

Related Questions