Adding elements to an xml file in C#

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

I have an XML file formatted like this:


  
    
      testcode1
    
  &l         


        
相关标签:
7条回答
  • 2020-11-27 19:17

    I've used XDocument.Root.Add to add elements. Root returns XElement which has an Add function for additional XElements

    0 讨论(0)
  • 2020-11-27 19:22
    <Snippet name="abc"> 
    

    name is an attribute, not an element. That's why it's failing. Look into using SetAttribute on the <Snippet> element.

    root.SetAttribute("name", "name goes here");
    

    is the code you need with what you have.

    0 讨论(0)
  • 2020-11-27 19:30

    Id be inclined to create classes that match the structure and add an instance to a collection then serialise and deserialise the collection to load and save the document.

    0 讨论(0)
  • 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(@"
            <Snippets>
    
              <Snippet name='abc'>
                <SnippetCode>
                  testcode1
                </SnippetCode>
              </Snippet>
    
              <Snippet name='xyz'>
                <SnippetCode>      
                 testcode2
                </SnippetCode>
              </Snippet>
    
            </Snippets>");
    
        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:

    <?xml version="1.0" encoding="utf-8"?>
    <Snippets>
      <Snippet name="abc">
        <SnippetCode>
          testcode1
        </SnippetCode>
      </Snippet>
      <Snippet name="xyz">
        <SnippetCode>      
         testcode2
        </SnippetCode>
      </Snippet>
      <Snippet name="name goes here">
        <SnippetCode>SnippetCode</SnippetCode>
      </Snippet>
    </Snippets>
    
    0 讨论(0)
  • 2020-11-27 19:35

    If you want to add an attribute, and not an element, you have to say so:

    XElement root = new XElement("Snippet");
    root.Add(new XAttribute("name", "name goes here"));
    root.Add(new XElement("SnippetCode", "SnippetCode"));
    

    The code above produces the following XML element:

    <Snippet name="name goes here">
      <SnippetCode>SnippetCode</SnippetCode>
    </Snippet> 
    
    0 讨论(0)
  • 2020-11-27 19:37

    You're close, but you want name to be an XAttribute rather than XElement:

     XDocument doc = XDocument.Load(spath); 
     XElement root = new XElement("Snippet"); 
     root.Add(new XAttribute("name", "name goes here")); 
     root.Add(new XElement("SnippetCode", "SnippetCode")); 
     doc.Element("Snippets").Add(root); 
     doc.Save(spath); 
    
    0 讨论(0)
提交回复
热议问题