Adding child nodes using c# Xdocument class

后端 未结 2 1758
我在风中等你
我在风中等你 2021-01-11 13:45

I have an xml file as given below.


 

  

         


        
相关标签:
2条回答
  • 2021-01-11 14:02
        Document.Root.Element("Characters").Add(new XElement("Character", new XAttribute("ID", "File0"), new XElement("Value", "value0"), new XElement("Description")),
            new XElement("Character", new XAttribute("ID", "File1"), new XElement("Value", "value1"), new XElement("Description")));
    

    Note: I have not included the namespace for brevity. You have to add those.

    0 讨论(0)
  • 2021-01-11 14:25

    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.

    0 讨论(0)
提交回复
热议问题