XML和C#在指定节点中加载属性

时间:2011-08-17 13:33:06

标签: c# xml

基本上我有这个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 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" />
  </drinks>
  <vitamins>

  </vitamins>
</items>

我希望能够在<item>中加载<items><food>的属性,并对每个<item>执行一些操作。我试过这样的事情(This),但它只适用于第一个<item>而不是其他3个。

1 个答案:

答案 0 :(得分:1)

我将使用XmlSerializer并定义与文档匹配的对象。像这样:

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; }
}

像这样使用:

public class Example
{
  static void Main()
  {
     using (Stream s = File.OpenRead("myfile.xml"))
     {
        Items myItems = (Items) new XmlSerializer(typeof (Items)).Deserialize(s);
     }
  }
}