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