Delete specific nodes under 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 extension nodes from XML. After deleting the process, it will be like this:

 <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 the error "The reference to the object is not installed in the instance of the object." for the string "root.Remove ()". How to remove extension nodes from an XML file? Thanks.

+6
source share
3 answers

Using:

Only remove 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(); 
+3
source

Sort of

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

You remove the parent of node from it ...

if you want to delete only expansion nodes, then basically you find deletion until terra are present in the thesaurus or return a list of them and go through the loop, removing them from the parent thesaurus.

0
source

You have no success because your thesaurus has a different namespace. You need to specify ti to make it work.

 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 is valid. The only thing you need to remove the non-root children is to achieve the desired results.

0
source

Source: https://habr.com/ru/post/906677/


All Articles