2012-12-28 106 views
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")]它不想工作。我做錯了什麼?

+1

http://stackoverflow.com/questions/4154621/add-xml-attribute-to-string-property嘗試此鏈接以及給你一個非常需要的例子序列化 - >反序列化 - http://stackoverflow.com/questions/10805344/how-to-deserialize-an-xml-string – MethodMan

回答

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

謝謝你的好例子! – Sergey

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