My XML is below;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
<diacritics_sensitive>1</diacritics_sensitive>
<expansion>
<sub>Internet Explorer</sub>
<sub>IE</sub>
<sub>IE5</sub>
</expansion>
<expansion>
<sub>run</sub>
<sub>jog</sub>
</expansion>
</thesaurus>
</XML>
I want to remove the "expansion" nodes from the XML. After removing process, it would be like that;
<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
</thesaurus>
</XML>
My code is below;
XDocument tseng = XDocument.Load("C:\\tseng.xml");
XElement root = tseng.Element("XML").Element("thesaurus");
root.Remove();
tseng.Save("C:\\tseng.xml");
I got an error "Object reference not set to an instance of an object." for line "root.Remove()". How can I remove the "expansion" nodes from XML file? Thanks.
To remove a node from the XML Document Object Model (DOM), use the RemoveChild method to remove a specific node. When you remove a node, the method removes the subtree belonging to the node being removed; that is, if it is not a leaf node.
To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.
The root node is the parent of all other nodes in the document. An immediate descendant of another node. Note that element attributes are not generally considered child elements.
While a properly formed XML file can only have a single root element, an XSD or DTD file can contain multiple roots.
Use:
Will remove only expansion
elements:
XNamespace ns = "x-schema:tsSchema.xml";
tseng.Root.Element(ns + "thesaurus")
.Elements(ns + "expansion").Remove();
Will remove all children of thesaurus
:
XNamespace ns = "x-schema:tsSchema.xml";
tseng.Root.Element(ns + "thesaurus").Elements().Remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With