3

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

 <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")]它不想工作。我做错了什么?

4

2 回答 2

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; }
}
于 2012-12-28T12:41:37.900 回答
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());
 }
于 2012-12-28T12:52:51.580 回答