Moving node in xdocument

I want to find the node attribute by attribute and move it from the bottom.

XNode node = doc.Root.Elements().Where(e => e.Attribute("id").Value == "123").FirstOrDefault(); if (node != null) { node.Root.Elements().Where(s => e.Attribute("id").Value == "123").Remove(); doc.Root.Add(node); } 

This does not always work. in the line .Remove () I sometimes get a nullReferenceException. Therefore, I assume that this means that it is mapped and got the node in FirstOrDefault (), but then the exact same linq query of two lines later didn't match anything. Not seeing how this is possible. Am I missing something? There is nothing related to this document or anything else.

+4
source share
1 answer

Please use this sample :

  var foos = (from xElem in xDoc.Root.Descendants("Foo") where xElem.Attribute("id").Value == "2" || xElem.Attribute("id").Value == "3" select xElem).ToList(); var newParentElem = (from xElem in xDoc.Root.Descendants("SubSection") where xElem.Attribute("id").Value == "C" select xElem).Single(); foreach(var xElem in foos) { xElem.Remove(); newParentElem.Add(xElem); } 
+1
source

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


All Articles