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
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
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.
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#.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly