Reputation: 31
I need to create single list from a xml file where there is some value from Parent and Some from Child node using Linq, Then i need bind this list in a single list view in UI
<item>
<name>AAA</name>
<id>94926DD03DB67FE30B456E50A0C34DF6</id>
<files>
<update>1533861455395</update>
<file>
<name>1532997455395.pdf</name>
<update>1532997455395</update>
</file>
<file>
<name>1533861455395.pdf</name>
<update>1533861455395</update>
</file>
</files>
</item>
<item>
<name>BBB</name>
<id>A16779822115170AECAD570D0139E8F3</id>
<files>
<file>
<name>1530405455395.pdf</name>
<update>1530405455395</update>
</file>
</files>
</item>
Code i've written where FileName showing properly but in Update value not returning
public void xml()
{
XDocument loadedData = XDocument.Load(xmlUrl);
var lstBooks = loadedData.Descendants("item").Select(x =>
new
{
FileName = x.Element("name").Value,
Update = x.Elements("files").Select(y => y.Element("update").Value),
}).ToList();
}
Upvotes: 1
Views: 556
Reputation: 34421
You have to create a flat datatable and fill in all columns like code below :
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Item Name", typeof(string));
dt.Columns.Add("Item ID", typeof(string));
dt.Columns.Add("Files Update", typeof(string));
dt.Columns.Add("File Name", typeof(string));
dt.Columns.Add("File Update", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement item in doc.Descendants("item"))
{
string name = (string)item.Element("name");
string itemID = (string)item.Element("id");
foreach (XElement files in item.Elements("files"))
{
string filesUpdate = (string)files.Element("update");
foreach (XElement file in files.Elements("file"))
{
string filename = (string)file.Element("name");
string fileUpdate = (string)file.Element("update");
dt.Rows.Add(new object[] { name, itemID, filesUpdate, filename, fileUpdate });
}
}
}
}
}
}
Upvotes: 0
Reputation: 1671
I think this is what you want (a list of objects containing filename and update value):
var lstBooks = loadedData.Descendants("file").Select(x =>
new {
FileName = x.Element("name").Value,
Update = x.Element("update").Value
}).ToList();
In case you want the item name and a list of updates, then use this:
var lstBooks = loadedData.Descendants("item").Select(x =>
new {
FileName = x.Element("name").Value,
Update = x.Elements("files").Select(y => y.Element("update").Value).ToList(),
}).ToList();
Upvotes: 1