XDocument removing nodes

19,125

Solution 1

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.

Solution 2

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().

Share:
19,125
user137348
Author by

user137348

Updated on July 14, 2022

Comments

  • user137348
    user137348 over 1 year

    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.

  • Drunken Code Monkey
    Drunken Code Monkey about 9 years
    Or the short form: xml...<beforeInit>.First.Remove()
  • Joe Phillips
    Joe Phillips about 7 years
    Should e.Name actually be e.Name.LocalName ?
  • Lutch
    Lutch almost 6 years
    @Stephan Schinkel how do i remove the all the head content if BeforeInit is present ?