XML and C# Load Attributes of in specified nodes
So basically I have this XML Doc
<?xml version="1.0" encoding="utf-8" ?>
<items>
<food>
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
</food>
<snaks>
</snaks>
<drinks>
<item Item开发者_JS百科Name="Hamburger" Cost="1.50" Image="hamburger.jpg" />
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
<item ItemName="Hamburger" Cost="1.50" Image="hamburger.jpg" />
</drinks>
<vitamins>
</vitamins>
</items>
I want to be able to load the Attributes of <item>
in <items><food>
and do something with with each <item>
. I tried something like this (This) but it only worked for the first <item>
not the other 3.
I'd use XmlSerializer and define an object matching the document. Something like this:
public class Item
{
[XmlAttribute("ItemName")]
public string Name { get; set; }
[XmlAttribute("Cost")]
public decimal Cost { get; set; }
[XmlAttribute("Image")]
public decimal Image { get; set; }
}
[XmlRoot("items")]
public class Items
{
[XmlArray("food")]
[XmlArrayItem("item")]
public List<Item> Food { get; set; }
[XmlArray("snaks")]
[XmlArrayItem("item")]
public List<Item> Snacks { get; set; }
[XmlArray("drinks")]
[XmlArrayItem("item")]
public List<Item> Drinks { get; set; }
[XmlArray("vitamins")]
[XmlArrayItem("item")]
public List<Item> Vitamins { get; set; }
}
Use it like this:
public class Example
{
static void Main()
{
using (Stream s = File.OpenRead("myfile.xml"))
{
Items myItems = (Items) new XmlSerializer(typeof (Items)).Deserialize(s);
}
}
}
精彩评论