Adding child nodes using c# Xdocument class
c#, xml
Solution
You're trying to add an extra `file:Character` element directly into the root. You don't want to do that - you want to add it under the `file:Characters` element, presumably.
Also note that `Descendants()` will never return null - it will return an empty sequence if there are no matching elements. So you want:
var ns = "test";
var file = Path.Combine(folderPath, "File.test");
var doc = XDocument.Load(file);
// Or var characters = document.Root.Element(ns + "Characters")
var characters = document.Descendants(ns + "Characters").FirstOrDefault();
if (characters != null)
{
characters.Add(new XElement(ns + "Character");
doc.Save(file);
}
Note that I've used more conventional naming, `Path.Combine`, and also moved the `Save` call so that you'll only end up saving if you've actually made a change to the document.
Problem
I have an xml file as given below. ``` <?xml version="1.0" encoding="utf-8"?> <file:Situattion xmlns:file="test"> <file:Properties> </file:Situattion> ``` I would like to add the child element file:Character using xDocument.So that my final xml would be like given below ``` <?xml version="1.0" encoding="utf-8"?> <file:Situattion xmlns:file="test"> <file:Characters> <file:Character file:ID="File0"> <file:Value>value0</file:Value> <file:Description> Description0 </file:Description> </file:Character> <file:Character file:ID="File1"> <file:Value>value1</file:Value> <file:Description> Description1 </file:Description> </file:Character> </file:Characters> ``` Code in c# i tried using Xdocument class is given below. ``` XNamespace ns = "test"; Document = XDocument.Load(Folderpath + "\\File.test"); if (Document.Descendants(ns + "Characters") != null) { Document.Add(new XElement(ns + "Character")); } Document.Save(Folderpath + "\\File.test"); ``` At line "`Document.Add(new XElement(ns + "Character"));`", I am getting an error: `"This operation would create an incorrectly structured document."`. How can I add the node under "`file:Characters`".