Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific nodes under the XML root?

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.

like image 316
mkacar Avatar asked Jan 23 '12 15:01

mkacar


People also ask

How do you remove a node in XML?

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.

How do I select a specific node in XML?

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.

What are root nodes in XML?

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.

How many root nodes are there in XML?

While a properly formed XML file can only have a single root element, an XSD or DTD file can contain multiple roots.


1 Answers

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();
like image 105
Kirill Polishchuk Avatar answered Oct 19 '22 04:10

Kirill Polishchuk