XML node search by string on different XML objects in C #

advertisements

I looking for a way to search and remove node by a name.

I have XML for example and I want to remove node <aRemove>

I tried using :

xmlDoc.SelectNodes("//aRemove");
xmlDoc.SelectNodes(".//aRemove");
xmlDoc.SelectNodes("a aRemove");

The XML file :

 <a>

        <a1>
           <a12>
                  <aRemove> </aRemove>
           </a12>

        </a1>

        <a2>

        <a2>

   </a>

It never find that node. My XML's are different...one have <aRemove> in <a1></a1> and other inside <b><b3></b3></b>.

EDIT: some of the nodes in some XML's have attributes, for example :

<a2=t655> </a2>

How can I search for a node by string and remove it it different XML's for every one?


This may be easy with System.Xml.Linq.

 var xml = XElement.Parse(xmlString);//alternatively, you can load xml from file with XElement.Load(filepath)
 xml.XPathSelectElements(".//aRemove").Remove();

Edit:

As Alexei Levenkov suggested in comment, if aRemove elements have namespaces associated with them, and you want to remove all elements with name aRemove, irrespective of to which namespace they belong, you may try with the xpath ".//*[local-name()='aRemove']. The code snippet with xml linq will be,

 var xml = XElement.Parse(xmlString);//alternatively, you can load xml from file with XElement.Load(filepath)
 xml.XPathSelectElements(".//*[local-name()='aRemove']").Remove();