我们有以下代码:
[Serializable] public class Class1 { [XmlElement("description")] public string Description { get; set; } } class Program { static void Main(string[] args) { var list = new List<Class1> {new Class1() {Description = "Desc1"},new Class1() {Description = "Desc2"}}; var serializer = new XmlSerializer(typeof(List<Class1>),new XmlRootAttribute("root")); var ms = new MemoryStream(); serializer.Serialize(ms,list); ms.Position = 0; var result = new StreamReader(ms).ReadToEnd(); } }
执行后我们将在’result’变量中有以下内容:
<?xml version="1.0"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Class1> <description>Desc1</description> </Class1> <Class1> <description>Desc2</description> </Class1> </root>
问题是:如何将xml元素名称从“Class1”更改为“Item1”而不改变类名?
解决方法
你可以使用
XmlTypeAttribute.TypeName
这个.
尝试这个为你Class1定义
[XmlType(TypeName = "Item1")] [Serializable] public class Class1 { [XmlElement("description")] public string Description { get; set; } }