質問

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?

役に立ちましたか?

解決

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`,

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top