Adding elements to an xml file in C#

前端 未结 7 1128
名媛妹妹
名媛妹妹 2020-11-27 19:00

I have an XML file formatted like this:


  
    
      testcode1
    
  &l         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 19:35

    You need to create a new XAttribute instead of XElement. Try something like this:

    public static void Test()
    {
        var xdoc = XDocument.Parse(@"
            
    
              
                
                  testcode1
                
              
    
              
                      
                 testcode2
                
              
    
            ");
    
        xdoc.Root.Add(
            new XElement("Snippet",
                new XAttribute("name", "name goes here"),
                new XElement("SnippetCode", "SnippetCode"))
        );
        xdoc.Save(@"C:\TEMP\FOO.XML");
    }
    

    This generates the output:

    
    
      
        
          testcode1
        
      
      
              
         testcode2
        
      
      
        SnippetCode
      
    
    

提交回复
热议问题