XML解析列表

本文关键字:列表 XML | 更新日期: 2023-09-27 18:16:55

[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>

但我想为根元素的名称:"雇员",而不是"ArrayOfEmployee"我怎样才能做到呢?

我想这样做,因为我有一个文件,结构看起来像:

<Employees>
    <Employee>
    ...
    </Employee>
    <Employee>
    ...
    </Employee>
</Employees>

XML解析列表

修改如下

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);

可以通过XmlRootAttribute设置元素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:

…root参数允许您替换默认对象的通过指定XmlRootAttribute;对象允许你设置不同的名称空间,元素名称,等等。

你可以用属性标记你的属性,使用XmlArray和XmlArrayItem属性