How to create a XML file using XDocument and LINQ in C#?
I have a three List开发者_如何学运维 in c# ,the variable names are l_lstData1,l_lstData2,l_lstData3
The File Structure is
<FileDetails>
<Date FileModified="29/04/2010 12:34:02" />
<Data Name="Data_1" DataList="India" Level="2" />
<Data Name="Data_2" DataList="chennai" Level="2" />
<Data Name="Data_3" DataList="hyderabad" Level="2" />
<Data Name="Data_4" DataList="calcutta" Level="2" />
<Data Name="Data_5" DataList="vijayawada" Level="1" />
<Data Name="Data_6" DataList="cochin" Level="1" />
<Data Name="Data_7" DataList="madurai" Level="0" />
<Data Name="Data_8" DataList="trichy" Level="0" />
</FileDetails>
The Values od 3 Lists are as follows :
l_lstData1[0] = "India";l_lstData1[1] = "chennai";l_lstData1[2] = "hyderabad";
l_lstData1[3] = "calcutta";
so the level attribute of the above XML(element : Data) has tha value = "2".
l_lstData2[0] = "vijayawada";l_lstData2[1] = "cochin";
so the level attribute of the above XML(element : Data) has tha value = "1".
l_lstData3[0] = "madurai";l_lstData3[1] = "trichy";
so the level attribute of the above XML(element : Data) has tha value = "0".
How can i create the XML using Xdocument and also using LINQ....Plz revert back me if u have any queries
Here's an alternative to Pramodh's solution, if I've understood it correctly:
// First build up a single list to work with, using an anonymous type
var singleList = l_lstData1.Select(x => new { Value = x, Level = 2})
.Concat(l_lstData2.Select(x => new { Value = x, Level = 1})
.Concat(l_lstData3.Select(x => new { Value = x, Level = 0});
var doc = new XDocument(
new XElement("FileDetails",
new XElement("Date",new XAttribute("FileModified", DateTime.Now)),
singleList.Select((item, index) => new XElement("Data",
new XAttribute("Name", "Data_" + (index + 1)),
new XAttribute("DataList", item.Value),
new XAttribute("Level", item.Level))));
Try like this:
XDocument TEMP = new XDocument(new XElement("FileDetails",
new XElement("Date",new XAttribute("FileModified", DateTime.Now.ToString())),
l_lstData1.Select(l => new XElement("Data",new XAttribute("Name","Data_"+(l_lstData1.IndexOf(l)+1).ToString()),
new XAttribute ("DataList",l.ToString()),
new XAttribute ("Level","Level2"))),
l_lstData2.Select(l => new XElement("Data",new XAttribute("Name","Data_"+(l_lstData2.Count + l_lstData2.IndexOf(l)+1).ToString()),
new XAttribute ("DataList",l.ToString()),
new XAttribute ("Level","Level1"))) ,
l_lstData3.Select(l => new XElement("Data",new XAttribute("Name", "Data_" + (l_lstData3.Count + l_lstData2.Count + l_lstData3.IndexOf(l) + 1).ToString()),
new XAttribute ("DataList",l.ToString()),
new XAttribute ("Level","Level0")))
));
TEMP.Save("TEMP.xml");
精彩评论