5

I would like to delete just this one 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 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>

I would be okay with deleting any one node at a time (since I put a loop to check for sample IDs that need to be deleted) Any help would be appreciated, thanks in advance.

Amy
  • 51
  • 1
  • 1
  • 2

3 Answers3

6
XmlElement el = (XmlElement)originalXml.SelectSingleNode("/Tests/Test/Sample[@id='544']");
            if (el != null) {
                el.ParentNode.RemoveChild(el);
                originalXml.Save(@"d:\file.xml");
            }
Deve
  • 181
  • 4
  • 14
4

Found this online with a simple search:

XmlNode node = document.SelectSingleNode("/Tests/Test/Sample[@id='544']");
node.ParentNode.RemoveChild(t);
document.Save();
koopajah
  • 23,792
  • 9
  • 78
  • 104
spinon
  • 10,760
  • 5
  • 41
  • 59
3

I haven't tested this code but it should work.

XmlDocument xDoc = new XmlDocument();
xDoc.Load("file.xml");
xDoc.RemoveChild(xDoc.SelectSingleNode("//Sample[@ID='554']"));
Adam P
  • 4,603
  • 6
  • 31
  • 40