Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting specific node in xml

Tags:

c#

xml

I need to delete specific employee node and also its child node based on the value of id. For example, here I need to delete employee tag with id="2".

<company>
    <employee>
        <id>1</id>
        <name>sa</name>
    </employee>
    <employee>
        <id>2</id>
        <name>ssa</name>
    </employee>
</company>
like image 347
SAK Avatar asked Jul 12 '10 14:07

SAK


2 Answers

Try this one

 XmlDocument xmlDoc = new XmlDocument();
 XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/root/XMLFileName[@ID="+nodeId+"]");
            if (nodeToDelete != null)
            {
                nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
            }
            xmlDoc.Save("XMLFileName.xml")
like image 106
Johnny Avatar answered Oct 23 '22 05:10

Johnny


Assuming you have loaded that into an XmlDocument named doc:

XmlElement el = (XmlElement)doc.SelectSingleNode("/company/employee[id=2]");
if(el != null) { el.ParentNode.RemoveChild(el); }
like image 35
Marc Gravell Avatar answered Oct 23 '22 06:10

Marc Gravell