简体   繁体   中英

How to serialize attribute

I am trying to deserialize this code

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

I've created a class:

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

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

Without attribute everything works, but I need the data from attribute " id " as well. Once I put [XmlAttribute("employee/id")] it doesn't want to work. What I am doing wrong?

I think you need following classes to deserialize that 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; }
}
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());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM