0
<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());
2
  • please have a look at my edits to the question Commented Sep 11, 2012 at 9:05
  • 1
    Do you have a special reason to use LINQ? To me it looks like an XSL-transformation is the thing to do it... Commented Sep 11, 2012 at 9:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@KishoreBorra, I don't know if there was a typo in my original post, but I tested it and reposted. Try the updated code
Yes. The above code is working. But in my case I have multiple Category tags with a parent tag with a name <MyDocument xmlns="urn:Mylines.xsd" >. would it be creating any problem?
I figured out the solution. Yes the namespace would cause an issue while querying. It needs to be queried little differently. Please refer to the below link. social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.