从ObservableCollection中的项创建XML

时间:2011-03-12 18:06:34

标签: c# wpf xml

我正在尝试在循环访问observablecollection时写入xml文件。然后我想将格式化的xml传递给我的模型,让它写入xml文件。以下是我到目前为止的情况:

       public void SaveXml(string path)
    {
        XElement xml;
        foreach (var item in Cards)
        {
            xml = new XElement("Card",
                    new XAttribute("name", item.Name),
                    new XElement("Type", item.Type),
                    new XElement("Image",
                    new XAttribute("path", item.Image)),
                    new XElement("Usage", item.Usage),
                    new XElement("Quantity", item.Quantity),
                    new XElement("Sell", item.Sell)
                    );
        }
        Game.Model.Deck decks = new Game.Model.Deck();
        //decks.SaveXml("writetest.xml", xml);

这样,XML文件将替换为每个新节点..如何将其添加到同一个xml xelement中以创建要发送到我的模型的节点列表?

提前致谢!

3 个答案:

答案 0 :(得分:1)

这是我用于将ObservableCollection(在别处更新)保存到.xml文件的确切代码:

ObservableCollection<Item> items;
items = (ObservableCollection<Item>)MainWindow.mcv.SourceCollection;
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Item>));
TextWriter textWriter = new StreamWriter(@"items.xml");
serializer.Serialize(textWriter, items);
textWriter.Close();

答案 1 :(得分:0)

你必须定义一个XML根元素来添加所有Card元素 - 这样的东西会起作用:

  public void SaveXml(string path)
  {
    XElement root = new XElement("Cards");
    foreach (var item in Cards)
    {
      var xml = new XElement("Card",
                 new XAttribute("name", item.Name),
                 new XElement("Type", item.Type),
                 new XElement("Image",
                 new XAttribute("path", item.Image)),
                 new XElement("Usage", item.Usage),
                 new XElement("Quantity", item.Quantity),
                 new XElement("Sell", item.Sell)
                );
      root.Add(xml);
    }
    root.Save(path);
    Game.Model.Deck decks = new Game.Model.Deck();
    //decks.SaveXml("writetest.xml", root);

答案 2 :(得分:0)

你可以让它变得更短更简单:

var elements = Cards.Select(card => new XElement("Card" /* etc etc */));
var doc = new XDocument(elements);
Game.Model.Deck decks = new Game.Model.Deck();
decks.SaveXml("writetest.xml", doc);