简体   繁体   English

使用模型进行xml序列化/反序列化

[英]xml serialization / deserialization using models

What I want to achieve is an XML output like: 我想要实现的是XML输出,例如:

<cars>
 <car id="0">
  <Type>1</Type>
  <Class>B</Class>
 </car>
 <car id="1">
  <Type>1</Type>
  <Class>B</Class>
 </car>
</cars>

All the car data is in seperate XML files. 所有汽车数据都存储在单独的XML文件中。 Part of the following code I can achieve reading this data into a dictionary using a car-model: 在以下代码的一部分中,我可以使用汽车模型将数据读取到字典中:

    public Dictionary<int, ModelCar> Car { get; }

    public Cars()
    {

        Car = new Dictionary<int, ModelCar>();

        foreach (var File in Directory.GetFiles(Folder, "*.xml", SearchOption.TopDirectoryOnly))
        {

            ModelCar item = new ModelCar().DeserializeFile(File);

            Car.Add(item.Id, item);

        }

    }

The problem is writing the dictionary 'Car' which holds all the car data to a combined XML output / input. 问题在于编写字典“ Car”,该字典将所有汽车数据保存到组合的XML输出/输入中。 Any hints / tutorial / example on how the model 'Cars' should look like and how to invoke? 关于“汽车”模型的外观以及如何调用的任何提示/教程/示例?

Edit: Looking into this post now - https://stackoverflow.com/a/19600156/8333405 编辑:现在看这篇文章-https: //stackoverflow.com/a/19600156/8333405

First, you need to fix your XML to have proper end tags, like this: 首先,您需要修复XML以使其具有正确的结束标记,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<cars>
  <car id="0">
    <Type>1</Type>
    <Class>Buick</Class>
  </car>
  <car id="1">
    <Type>1</Type>
    <Class>B</Class>
  </car>
</cars>

Then you can let Visual Studio creates your model for you. 然后,您可以让Visual Studio为您创建模型。

  1. Copy you XML file contents. 复制您的XML文件内容。

  2. From Visual Studio Menus select Edit -> Paste Special -> Paste XML as Classes . 从Visual Studio菜单中选择“ 编辑”->“选择性粘贴”->“将XML粘贴为类”

Now, Visual Studio generated your models. 现在,Visual Studio生成了您的模型。 To use them use this code: 要使用它们,请使用以下代码:

// you do not need a dictionary. A List will do it.
List<carsCar> allCars = new List<carsCar>();

string folder = @"G:\Projects\StackOverFlow\WpfApp2";

foreach (var file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
    FileStream reader = File.OpenRead(file);
    XmlSerializer ser = new XmlSerializer(typeof(cars));
    cars cars = (cars)ser.Deserialize(reader);

    allCars.AddRange(cars.car);
}

// if you want the car with id = 0
var car_0 = allCars.FirstOrDefault(c => c.id == 0);

Try following using XML Linq 尝试遵循使用XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Cars cars = new Cars();
            XElement xCars = cars.Serialize();
        }
    }
    public class Cars
    {
        public Dictionary<int, ModelCar> Car { get; set; }


        public Cars()
        {

            Car = new Dictionary<int, ModelCar>() {
                {0, new ModelCar() { _class = "B", _type = 1, id = 0}},
                {1, new ModelCar() { _class = "B", _type = 1, id = 1}}
            };
        }
        public XElement Serialize()
        {
            return new XElement("cars", Car.AsEnumerable().Select(x => new XElement("car", new object[] {
                new XAttribute("id", x.Key),
                new XElement("Type", x.Value._type),
                new XElement("Class", x.Value._class)
            })));
        }
    }
    public class ModelCar
    {
        public int id { get; set; }
        public int _type { get; set; }
        public string _class { get;set; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM