Reputation: 1786
[XmlRoot("Employees")]
public class Employee
{
[XmlElement("EmpId")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
and simple method, which return 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);
I have file result:
<?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>
but i would like for Root Element has name: "Employees", not "ArrayOfEmployee" how can i make it?
I want to do it, because i have file, where structure looks like:
<Employees>
<Employee>
...
</Employee>
<Employee>
...
</Employee>
</Employees>
Upvotes: 0
Views: 111
Reputation: 3542
You can mark your property with attributes, use the XmlArray and XmlArrayItem attribute
Upvotes: 0
Reputation: 116168
Just change as below
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>),
new XmlRootAttribute("Employees"));
that's all. But to get a clean xml as in your question (no xml declaration, no xsi or xsd namespaces etc.), you should use a few tricks
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);
Upvotes: 2
Reputation: 20589
You can pass the XmlRootAttribute
to set the element Name:
var root = new XmlRootAttribute("Employees");
XmlSerializer ser = new XmlSerializer(typeof(List<Employee>), root);
TextWriter writer = new StreamWriter("nowi.xml");
ser.Serialize(writer, list);
From http://msdn.microsoft.com/en-us/library/f1wczcys%28v=vs.110%29.aspx :
... the root parameter allows you to replace the default object's information by specifying an XmlRootAttribute; the object allows you to set a different namespace, element name, and so on.
Upvotes: 1