我无法使用 XmlSerializer 生成以下 XML 结构:
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>This is root.</Name>
<OtherValue>Otha.</OtherValue>
<Shapes Name="This attribute is ignored!">
<Circle>
<Name>This</Name>
<Value>Is</Value>
<Whatever>Circle</Whatever>
</Circle>
<Square>
<Name>And</Name>
<Value>this is</Value>
<Something>Square</Something>
</Square>
</Shapes>
</Root>
唯一的问题是<Shapes>
没有写入的属性。我用于序列化的类如下:
public class Root
{
[XmlElement]
public string Name { get; set; }
[XmlElement]
public string OtherValue { get; set; }
[XmlArray("Shapes")]
[XmlArrayItem("Circle", typeof(Circle))]
[XmlArrayItem("Square", typeof(Square))]
public ShapeList Shapes { get; set; }
}
public class ShapeList : List<Shape>
{
// Attribute that is not in output
[XmlAttribute]
public string Name { get; set; }
}
public class Shape
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Circle : Shape
{
public string Whatever { get; set; }
}
public class Square : Shape
{
public string Something { get; set; }
}
还有一个运行序列化的主要方法:
public static void Main(String[] args)
{
var extraTypes = new Type[] {
typeof(Shape),
typeof(Square),
typeof(Circle)
};
var root = new Root();
root.Name = "This is root.";
root.OtherValue = "Otha.";
root.Shapes = new ShapeList()
{
new Circle() { Name = "This", Value="Is", Whatever="Circle" },
new Square() { Name = "And", Value="this is", Something="Square" }
};
root.Shapes.Name = "This is shapes.";
using (var sw = new StreamWriter("data.xml"))
{
var serializer = new XmlSerializer(typeof(Root), extraTypes);
serializer.Serialize(sw, root);
}
}
- 为什么我没有得到ShapeList的Name属性?
- 如果使用这种方法无法完成,还有其他简单的方法吗?