Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument removing nodes

Tags:

c#

linq-to-xml

I have a XML file

<rows>
  <head>
    <beforeInit>
      <call command="attachHeader">
        <param>#text_filter,#text_filter,#text_filter,#text_filter,#text_filter,#text_filter</param>
      </call>
    </beforeInit>
    <afterInit>
      <call command="enablePaging">
        <param>recinfoArea</param>
      </call>
     </afterInit>
    <column width="100" align="center" type="ro" sort="server" color="undefined" id="Id">Id</column>
    <column width="100" align="center" type="ro" sort="server" color="undefined" id="NazovProjektu">NazovProjektu</column>
   </head>
</rows>

I'd like to remove the beforeInit and afterInit elements.

I tried

xml.Elements().Where(e=>e.Name == "beforeInit" || e.Name == "afterInit").Remove();

but no luck.

like image 591
user137348 Avatar asked Dec 21 '10 14:12

user137348


Video Answer


2 Answers

if you want to delete every occurence of beforeInit or afterInit you could use

xml.Descendants().Where(e=>e.Name == "beforeInit" || e.Name == "afterInit").Remove();

(descendants instead of elements). elements() returns a list of direct child nodes, whereas descendants returns every node.

like image 127
Stephan Schinkel Avatar answered Sep 28 '22 01:09

Stephan Schinkel


If xml is a XElement, try:

xml.Element("head").Elements().Where(e=>e.Name == "beforeInit" || e.Name == "afterInit").Remove();

Otherwise, if it's an XDocument:

xml.Root.Element("head").Elements().Where(e=>e.Name == "beforeInit" || e.Name == "afterInit").Remove();

The way it is now, it's set up to look for the sub elements in <rows>, not <head>. In other words Elements() only returns the direct children of a node. If you want all the descendants, no matter what level, you want Descendants().

like image 40
James Sulak Avatar answered Sep 28 '22 01:09

James Sulak