XML file creation using XDocument in C#

前端 未结 2 647
故里飘歌
故里飘歌 2020-11-29 18:03

I have a List \"sampleList\" which contains

Data1
Data2
Data3...

The file structure is like

<         


        
相关标签:
2条回答
  • 2020-11-29 18:30

    Using the .Save method means that the output will have a BOM, which not all applications will be happy with. If you do not want a BOM, and if you are not sure then I suggest that you don't, then pass the XDocument through a writer:

    using (var writer = new XmlTextWriter(".\\your.xml", new UTF8Encoding(false)))
    {
        doc.Save(writer);
    }
    
    0 讨论(0)
  • 2020-11-29 18:45

    LINQ to XML allows this to be much simpler, through three features:

    • You can construct an object without knowing the document it's part of
    • You can construct an object and provide the children as arguments
    • If an argument is iterable, it will be iterated over

    So here you can just do:

    void Main()
    {
        List<string> list = new List<string>
        {
            "Data1", "Data2", "Data3"
        };
    
        XDocument doc =
          new XDocument(
            new XElement("file",
              new XElement("name", new XAttribute("filename", "sample")),
              new XElement("date", new XAttribute("modified", DateTime.Now)),
              new XElement("info",
                list.Select(x => new XElement("data", new XAttribute("value", x)))
              )
            )
          );
    
        doc.Save("Sample.xml");
    }
    

    I've used this code layout deliberately to make the code itself reflect the structure of the document.

    If you want an element that contains a text node, you can construct that just by passing in the text as another constructor argument:

    // Constructs <element>text within element</element>
    XElement element = new XElement("element", "text within element");
    
    0 讨论(0)
提交回复
热议问题