Kishore Borra
Kishore Borra

Reputation: 269

Linq query to select all the nodes based on an attribute value

<Category id=1>
<MyLines>
      <Line GroupID="0" Cache="15" />
  <Rect GroupID="0" Cache="16"/>
  <Ellipse GroupID="0" Cache="16"/>
</MyLines>

My XML document contains many Category tags. Could you please let me know what is the best way to get each of the sub elements of MyLines whose Cache = 16 and remove them.

I am looking to achieve this using linq.

I was trying as below:

       var q = from node in doc.Descendants("MyLines")
                let attr = node.Attribute("Cache")
                where attr != null && Convert.ToInt32(attr.Value) == 16
                select node;
        q.ToList().ForEach(x => x.Remove());

Upvotes: 0

Views: 764

Answers (1)

smartcaveman
smartcaveman

Reputation: 42246

I have tested the following code:

string xml = 
@"<Category id=""1"">
<MyLines>
    <Line GroupID=""0"" Cache=""15"" />
<Rect GroupID=""0"" Cache=""16""/>
<Ellipse GroupID=""0"" Cache=""16""/>
</MyLines>
</Category>";

void Main()
{
    var doc = XDocument.Parse(xml);

    doc.Descendants("MyLines")
    .Elements()
    .Where(el => el.Attribute("Cache").Value == "16") 
    .ToList()
    .ForEach(el => el.Remove());

    doc.Root.ToString().Dump();
}

It prints:

<Category id="1">
   <MyLines>
      <Line GroupID="0" Cache="15" />
   </MyLines>
</Category>

The problem is that you were looking for the Cache attribute on the MyLines elements instead of on the MyLines elements' children.

Upvotes: 2

Related Questions