kharagpur
kharagpur

Reputation: 241

Remove XML node if the inner tag matches value using Linq in C#

<column>
    <format>boolicon</format>
    <heading>Attachment</heading>
    <prop>urn:schemas:httpmail:hasattachment</prop>
    <type>boolean</type>
    <bitmap>1</bitmap>
    <width>10</width>
    <style>padding-left:3px;text-align:center</style>
    <editable>0</editable>
    <displayformat>3</displayformat>
</column>
<column>
    <heading>From</heading>
    <prop>urn:schemas:httpmail:fromname</prop>
    <type>string</type>
    <width>68</width>
    <style>padding-left:3px;text-align:left</style>
    <editable>0</editable>
    <displayformat>1</displayformat>
</column>
<column>
    <heading>Subject</heading>
    <prop>urn:schemas:httpmail:subject</prop>
    <type>string</type>
    <width>326</width>
    <style>padding-left:3px;text-align:left</style>
    <editable>1</editable>
</column>

I want to delete column node if the heading is equal to "Subject"

(from node in xdoc.Descendants("column") select node).ToList().ForEach(x=>x.Remove());

Trying to select node only if it heading matches "Subject".

Thanks in advance.

Upvotes: 2

Views: 306

Answers (2)

har07
har07

Reputation: 89325

You can add simple where clause to filter only <column> elements having child <heading> equals "Subject" :

(from node in xdoc.Descendants("column") 
 where (string)node.Element("heading") == "Subject" 
 select node
 ).Remove();

Or using method syntax :

xdoc.Descendants("column")
    .Where(n => (string)n.Element("heading") == "Subject")
    .Remove();

Upvotes: 3

EZI
EZI

Reputation: 15364

I think, a simple XPath can help you

xdoc.XPathSelectElement("//column[heading='Subject']").Remove();

PS: Don't forget to include using System.Xml.XPath;

Upvotes: 5

Related Questions