How to create XML document using XDocument in C#?


Hello, I need to add some data in XML file by programmatically creating it using C# and XDocument, so how I will create it?

For example, Suppose if I need output like below in XML

<NewFile>
   <name filename="XMLSample"/>
   <MainInfo>
     <data value="Value1"/> 
     <data value="Value2"/>
     <data value="Value3"/>
   </MainInfo>
</NewFile>

Any link or Code sample?

Thanks


Asked by:- Sam
0
: 13491 At:- 4/7/2018 12:05:41 PM
C# ASP.NET XML Xdocument







2 Answers
profileImage Answered by:- pika

You can create the XML file using Linq to XML (XDocument) in C# like below

 XDocument document = new XDocument(
            new XDeclaration("0.1", "utf-8", "yes"),
            new XElement("NewFile",
              new XElement("name",new XAttribute("filename", "XMLSample")),
                new XElement("MainInfo",
                   new XElement("data", new XAttribute("value", "Value1")),
                   new XElement("data",new XAttribute("value", "Value2")),
                   new XElement("data", new XAttribute("value", "Value3"))
                   )
               )

           );

            document.Save(Server.MapPath("~/XMLSample.xml"));

as you see in the above code XElement create a new element in your XML doc, while XAttribute("dataName","Value") create attributes and value of the node.

Output

XML-file-create-using-XDocument -in-c-sharp.png

Another Way

If you have a list of data and you need to convert it into XML attribute you can use generate the same XML like above using below C# code also

List<string> list = new List<string>
                {
                    "Value1", "Value2", "Value3"
                };

            XDocument document = new XDocument(
            new XDeclaration("0.1", "utf-8", "yes"),
            new XElement("NewFile",
              new XElement("name",new XAttribute("filename", "XMLSample")),
                new XElement("MainInfo",
                    list.Select(x => new XElement("data", new XAttribute("value", x)))
                   )
               )

           );

            document.Save(Server.MapPath("~/XMLSample.xml"));

That's it.

2
At:- 4/7/2018 5:48:36 PM
Thanks for the perfect answer 0
By : Sam - at :- 4/12/2018 1:13:16 PM


profileImage Answered by:- bhanu

XmlWriter is the fastest way to write good XML,but if you want to do it using XDocument, you can simply do this

Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));

There is more detailed description of creating XML in C#, you can check here

Create XML document using C# (Console Application example)

Or you can also check about open and read XML in C#.

0
At:- 4/8/2021 11:04:47 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use