Adding child nodes using c# Xdocument class

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

I have an xml file as given below.


 

  

         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    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.

提交回复
热议问题