我正在尝试在序列化
XML时获得此结果
<Test> <Category> <FileName>C:\test.txt</FileName> <!-- Note that here this is an array of a simple class with two fields without root --> <Prop1>1</Prop1> <Prop2>2</Prop2> <Prop1>4</Prop1> <Prop2>5</Prop2> <!-- End array --> </Category> </Test>
我已经尝试过不同的东西了
[Serializable] [XmlRoot("Test")] public class Test { [XmlElement("Category")] public List<Category> Category= new List<Category>(); } [Serializable] [XmlRoot("Category")] public class Category { [XmlElement("FileName")] public string FileName { get; set; } [XmlElement("Property")] public List<Property> Properties = new List<Property>(); } [Serializable] public class Property { public string Prop1 { get; set; } public string Prop2 { get; set; } }
但是我仍然得到这个输出:
<Test> <Category> <FileName>C:\test.txt</FileName> <Property> <Prop1>1</Prop1> <Prop2>2</Prop2> </Property> <Property> <Prop1>4</Prop1> <Prop2>5</Prop2> </Property> </Category> </Test>
解决方法
如果您真的需要确切的输出,如上所述,您可以使用以下解决方法:
[Serializable] public partial class Test { public List<Category> Category; } [Serializable] public partial class Category { [XmlElement("FileName")] public string FileName; [XmlElement("Prop1")] [XmlElement("Prop2")] [XmlChoiceIdentifier("propName")] public string[] Properties; [XmlIgnore] public PropName[] propName; } public enum PropName { Prop1,Prop2,}