I have a List \"sampleList\" which contains
Data1
Data2
Data3...
The file structure is like
<
LINQ to XML allows this to be much simpler, through three features:
So here you can just do:
void Main()
{
List list = new List
{
"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 text within element
XElement element = new XElement("element", "text within element");