简体   繁体   中英

xml serialization / deserialization using models

What I want to achieve is an XML output like:

<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. 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. 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

First, you need to fix your XML to have proper end tags, like this:

<?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.

  1. Copy you XML file contents.

  2. From Visual Studio Menus select Edit -> Paste Special -> Paste XML as Classes .

Now, Visual Studio generated your models. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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