如何序列化属性

时间:2012-12-28 12:38:19

标签: c# xml serialization

我正在尝试反序列化此代码

 <request>
  <employee id="40407">Test User</employee>
 </request>

我创建了一个类:

public class Request
{
    public string employee { get; set; }

    [XmlAttribute("employee/id")]
    public string employeeId { get; set; }
}

没有属性一切正常,但我也需要来自属性“id”的数据。一旦我放[XmlAttribute("employee/id")]它就不想工作了。我做错了什么?

2 个答案:

答案 0 :(得分:4)

我认为您需要以下类来反序列化xml:

[XmlRoot("request")]
public class Request
{
    [XmlElement("employee")]
    public Employee Employee { get; set; }
}

[XmlRoot("employee")]
public class Employee
{
    [XmlText]
    public string Name { get; set; }

    [XmlAttribute("id")]
    public string EmployeeId { get; set; }
}

答案 1 :(得分:1)

public class empl
{
     [XmlText]
     public string name { get; set; }
     [XmlAttribute]
     public int id { get; set; }
 }

 public class request
 {
      public empl employee { get; set; }
 }


 public Test()
 {
    XmlSerializer ser = new XmlSerializer(typeof(request));
    MemoryStream mem = new MemoryStream();
    ser.Serialize(mem , new request { employee = new empl { name="ff", id=6}});
    string dec = UTF8Encoding.UTF8.GetString(mem.ToArray());
 }