XDocument removing nodes

2020-07-16 06:43发布

问题:

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.

回答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.



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