mkacar
mkacar

Reputation: 277

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.

Upvotes: 6

Views: 1975

Answers (3)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

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();

Upvotes: 3

Samich
Samich

Reputation: 30115

You have no success because your thesaurus have different namespace. You need to specify ti to get it works.

XNamespace ns = "x-schema:tsSchema.xml";
XDocument tseng = XDocument.Parse(xml);

XElement root = tseng.Element("XML").Element(ns + "thesaurus");
root.Elements().Remove();

In general your code valid. The only thing that you need to delete child elements not root to reach results you needed.

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Something like

XElement root = tseng.Element("XML").Element("thesaurus"); 
tseng.Element("XML").Remove(thesaurus);

You remove a node from it's parent...

if you want to remove just the expansion nodes, then basically you find a remove until tere aren't any in thesaurus, or return a list of them and loop through removing them from their parent thesaurus.

Upvotes: 0

Related Questions