Sample2 from ...">

Remove node child with RemoveChild ()

I would like to remove only this node, for example:

<Sample ID="544" Type="0">Sample2</Sample>

from this XML, for example:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="544" Type="0">Sample2</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

so that my results are something like this:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

It would be nice for me to remove any node at a time (since I set up a loop to check the identifiers of the samples to be removed) Any help would be appreciated, thanks in advance.

+3
source share
3 answers
XmlElement el = (XmlElement)originalXml.SelectSingleNode("/Tests/Test/Sample[@id='544']");
            if (el != null) {
                el.ParentNode.RemoveChild(el);
                originalXml.Save(@"d:\file.xml");
            }
+5
source

Found it online with a simple search:

XmlNode node = document.SelectSingleNode("/Tests/Test/Sample[@id='544']");
node.ParentNode.RemoveChild(t);
document.Save();
+2
source

I have not tested this code, but it should work.

XmlDocument xDoc = new XmlDocument();
xDoc.Load("file.xml");
xDoc.RemoveChild(xDoc.SelectSingleNode("//Sample[@ID='554']"));
+2
source

Source: https://habr.com/ru/post/1754740/


All Articles