我有一个格式如下的 XML:http://pastie.org/1311506 (不在此处插入它,因为注释解析器会删除标签)。
此 XML 使用以下代码进行序列化/反序列化:
[XmlRoot("products")]
public class Products
{
[XmlElement("label")]
public string Label { get; set; }
[XmlArray("cars")]
[XmlArrayItem("car")]
public Car[] Cars { get; set; }
}
public class Car
{
[XmlAttribute("name")]
public string Name { get; set; }
}
...
var products = new Products
{
Label = "1",
Cars = new[]
{
new Car {Name = "BMW"},
new Car {Name = "Volvo"}
}
};
var serializer = new XmlSerializer(typeof(Products));
var writer = new StringWriter();
serializer.Serialize(writer, products);
Console.WriteLine(writer);
我需要 <cars> 的附加属性节点名为 type (就像这里:http://pastie.org/1311514)。我该怎么做?
换句话说,如何定义数据类(Products 和 Car,如果需要可能还有其他)以解析第二个 pastie 链接中显示的格式的 XML?
请您参考如下方法:
没有简单的方法可以做到这一点,因为对于集合,XmlSerializer 忽略所有成员,它只序列化集合的项目。但是,如果您只想反序列化它并忽略 type 属性,这不是问题:未知属性将被忽略。
如果需要获取type的值,可以声明一个不是集合但包含集合的类。类似的东西:
public class Cars
{
[XmlElement("car")]
public Car[] Items { get; set; }
[XmlAttribute("type")]
public string Type { get; set; }
}
在您的 Products 类中,只需使用 XmlElement 属性声明 Cars 类型的 Cars 属性:
[XmlRoot("products")]
public class Products
{
[XmlElement("label")]
public string Label { get; set; }
[XmlElement("cars")]
public Cars Cars { get; set; }
}
