0

我有一个来自外部源的 xml 文档,所以我无法更改结构。我需要将其序列化为 C# 对象:-

<vehicles>
   <Car>
       <Vauxhall>
          <Driver>
             <Name>John</Name>
          </Driver>
   </Car>
   <Car>
       <Ford>
         <Driver>
            <Name>Jack</Name>
         </Driver>
       </Ford>
   </Car>
</vehicles>

任何人都可以为上述简单的 xml 文档提供 C# 反序列化类的建议吗?

4

2 回答 2

0
Public Class Wheels
{
  <XmlAttribute()>
  public string CarMake;
  //If you want to have a value in your "Wheels"
  <XmlText()>
  public string Value;
}

设置CarMake为沃克斯豪尔,你应该得到:

<Vehicle>
  <Car CarMake="Vauxhall"\>
<Vehicle>

例如,如果你设置Value你的,你会得到:WheelsAstra

<Vehicles>
  <Car CarMake="Vauxhall">Astra<Car/>
<Vehicles>

编辑

看到你想要的整体结构后,你会有这样的东西:

public class Test
{
   <XmlArray("Vehicles")>
   <XmlArrayItem("Car")>
   public List<Wheel> Wheels = new List<Wheel>();
}
于 2012-12-04T16:51:29.147 回答
0

您应该能够创建一个通用的 Car 类,然后为每个特定的品牌隐含该类 - 很糟糕,但是如果您无法更改 xml,我不知道您还能怎么做

public class Car
{
    private Driver _driver;

    public Driver Driver
    {
        get
        {
            return _driver;
        }
        set
        {
            _driver = value;
        }
    }
}

public class Driver
{
    private string _name;

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }
}

public class Vauxhall : Car
{
}

public class Ford : Car
{
}
于 2012-12-04T17:09:16.123 回答