[XmlRoot("Employees")]
public class Employee
{
[XmlElement("EmpId")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
和简单的方法,返回List:
public static List<Employee> SampleData()
{
return new List<Employee>()
{
new Employee(){
Id = 1,
Name = "pierwszy"
},
new Employee(){
Id = 2,
Name = "drugi"
},
new Employee(){
Id = 3,
Name = "trzeci"
}
};
}
的Program.cs:
var list = Employee.SampleData();
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>));
TextWriter writer = new StreamWriter("nowi.xml");
ser.Serialize(writer, list);
我有文件结果:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Employee>
<EmpId>1</EmpId>
<Name>pierwszy</Name>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>drugi</Name>
</Employee>
<Employee>
<EmpId>3</EmpId>
<Name>trzeci</Name>
</Employee>
</ArrayOfEmployee>
但我想Root Element的名称是:“Employees”,而不是“ArrayOfEmployee” 我该怎么做?
我想这样做,因为我有文件,结构如下:
<Employees>
<Employee>
...
</Employee>
<Employee>
...
</Employee>
</Employees>
答案 0 :(得分:2)
只需更改如下
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>),
new XmlRootAttribute("Employees"));
全部。但是要在你的问题中得到一个干净的xml(没有xml声明,没有xsi或xsd命名空间等),你应该使用一些技巧
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>),
new XmlRootAttribute("Employees"));
TextWriter writer = new StreamWriter(filename);
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true });
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
ser.Serialize(xmlWriter, list, ns);
答案 1 :(得分:1)
您可以传递XmlRootAttribute
来设置元素名称:
var root = new XmlRootAttribute("Employees");
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>), root);
TextWriter writer = new StreamWriter("nowi.xml");
ser.Serialize(writer, list);
来自http://msdn.microsoft.com/en-us/library/f1wczcys%28v=vs.110%29.aspx:
... root参数允许您替换默认对象 通过指定XmlRootAttribute来获取信息;该对象允许你 设置不同的命名空间,元素名称,等等。
答案 2 :(得分:0)
您可以使用属性标记属性,使用XmlArray和XmlArrayItem属性