繁体   English   中英

XML序列化包含对象列表的对象列表

[英]XML Serializing list of objects containing list of objects

我的对象结构类似于下面的简化代码。 请注意,国家和汽车都必须是类,由于示例中未包含代码,所以我无法使用字符串列表/数组。 我想对XML进行序列化,然后反序列化对象。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace XMLapp
{
    public partial class Form1 : Form
    {
        List<Countries> Country = new List<Countries>();
        List<string> cars = new List<string>();

        public Form1()
        {
            InitializeComponent();

            cars.Add("Audi");
            cars.Add("BMW");
            cars.Add("Mercedes");
            addCountry("Germany", cars);

            cars.Clear();
            cars.Add("Ford");
            cars.Add("Chevrolet");
            cars.Add("Jeep");
            addCountry("USA", cars);

            TestXmlSerialize();
            Console.WriteLine("Generated list");
        }

        void TestXmlSerialize()
        {
            XmlSerializer x = new XmlSerializer(Country.GetType());
            x.Serialize(Console.Out, Country);
        }

        void addCountry(string name, List<string> cars)
        {
            Countries newCountry = new Countries();
            newCountry.Name = name;
            newCountry.AddCar(cars);
            Country.Add(newCountry);
        }
    }

    public class Countries
    {
        public string Name { get; set; }
        List<Cars> car = new List<Cars>();

        public void AddCar(List<string> cars)
        {
            for (int i = 0; i < cars.Count; i++)
            {
                Cars newCar = new Cars();
                newCar.brand = cars[i];
                car.Add(newCar);
            }
        }

        class Cars
        {
            public string brand;
        }

    }
}

生成以下输出:

<?xml version="1.0" encoding="IBM437"?>
<ArrayOfCountries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Countries>
    <Name>Germany</Name>
  </Countries>
  <Countries>
    <Name>USA</Name>
  </Countries>
</ArrayOfCountries>

但是,我期望有些类似

  <Countries>
    <Name>Germany</Name>
    <ArrayOfCars>
      <Brand>Audi</Brand>
      <Brand>BMW</Brand>
      <Brand>Mercedes</Brand>
    </ArrayOfCountries>
  </Countries>

我可以看到汽车品牌已正确存储在“本地与汽车”窗口中,但是如何在序列化中包括它们?

XmlSerializer仅序列化公共字段和属性。 您需要公开“汽车”字段和“汽车”类别。

它不会产生您在问题中发布的确切xml布局,但是它将允许您序列化和反序列化对象。

暂无
暂无

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

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