문제

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