Hi in this post i'll explain you how to read an xml file and making the nodes to list to your model class values.
for example if you XML is in format of follow :
<items>
<item id="43">
<name>
Large Hammer
</name>
<quantity>
1
</quantity>
<unitprice>
15.95
</unitprice>
</item>
<item id="54">
<name>
Ladder
</name>
<quantity>
2
</quantity>
<unitprice>
40.95
</unitprice>
</item>
<item id="68">
<name>
Paint
</name>
<quantity>
10
</quantity>
<unitprice>
18.95
</unitprice>
</item>
</items>
for the above you just need to make the read the xml first and
string startupPath = AppDomain.CurrentDomain.BaseDirectory + "\\files\\export.xml";
var Xmlmaps = XDocument.Load((startupPath));
var dictionary = Xmlmaps.Descendants("Item").ToList();
List<Item> mapList = new List<Item>();
foreach (var item in dictionary)
{
mapList.Add(new Item()
{
Name = item.Descendants("name").FirstOrDefault().FirstAttribute.Value,
quantity= item.Descendants("quantity").FirstOrDefault().FirstAttribute.Value,
unitprice = item.Descendants("unitprice").FirstOrDefault().FirstAttribute.Value,
});
}
here in the above code it first we are reading file from "C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer/11.0"
then that gives the resultant nodes into dictionary trpe of Xelements. then we are reading inner child nodes and saving the each type into the type of "Item" then the result of "MapList" will gives you the list of all Items in the Xml then from that list you can do what ever depends in your need.
for example if you XML is in format of follow :
<items>
<item id="43">
<name>
Large Hammer
</name>
<quantity>
1
</quantity>
<unitprice>
15.95
</unitprice>
</item>
<item id="54">
<name>
Ladder
</name>
<quantity>
2
</quantity>
<unitprice>
40.95
</unitprice>
</item>
<item id="68">
<name>
Paint
</name>
<quantity>
10
</quantity>
<unitprice>
18.95
</unitprice>
</item>
</items>
for the above you just need to make the read the xml first and
string startupPath = AppDomain.CurrentDomain.BaseDirectory + "\\files\\export.xml";
var Xmlmaps = XDocument.Load((startupPath));
var dictionary = Xmlmaps.Descendants("Item").ToList();
List<Item> mapList = new List<Item>();
foreach (var item in dictionary)
{
mapList.Add(new Item()
{
Name = item.Descendants("name").FirstOrDefault().FirstAttribute.Value,
quantity= item.Descendants("quantity").FirstOrDefault().FirstAttribute.Value,
unitprice = item.Descendants("unitprice").FirstOrDefault().FirstAttribute.Value,
});
}
here in the above code it first we are reading file from "C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer/11.0"
then that gives the resultant nodes into dictionary trpe of Xelements. then we are reading inner child nodes and saving the each type into the type of "Item" then the result of "MapList" will gives you the list of all Items in the Xml then from that list you can do what ever depends in your need.
No comments:
Post a Comment