2013-02-01 53 views
19

Tôi đang cố chuyển đổi kết quả tôi nhận được từ dịch vụ web của mình thành chuỗi và chuyển đổi nó thành một đối tượng.Deserializing XML từ chuỗi

Đây là chuỗi tôi nhận được từ dịch vụ của tôi:

<StatusDocumentItem><DataUrl/><LastUpdated>2013-01-31T15:28:13.2847259Z</LastUpdated><Message>The processing of this task has started</Message><State>1</State><StateName>Started</StateName></StatusDocumentItem> 

Vì vậy, tôi có một lớp học cho điều này như:

[XmlRoot] 
public class StatusDocumentItem 
{ 
    [XmlElement] 
    public string DataUrl; 
    [XmlElement] 
    public string LastUpdated; 
    [XmlElement] 
    public string Message; 
    [XmlElement] 
    public int State; 
    [XmlElement] 
    public string StateName; 
} 

Và đây là cách tôi đang cố gắng để có được điều đó chuỗi như một đối tượng thuộc loại StatusDocumentItem với XMLDeserializer (NB. operationXML chứa chuỗi):

string operationXML = webRequest.getJSON(args[1], args[2], pollURL); 
var serializer = new XmlSerializer(typeof(StatusDocumentItem)); 
StatusDocumentItem result; 

using (TextReader reader = new StringReader(operationXML)) 
{ 
    result = (StatusDocumentItem)serializer.Deserialize(reader); 
} 

Console.WriteLine(result.Message); 

Nhưng của tôi đối tượng kết quả luôn trống. Tôi đang làm gì sai?

Cập nhật. Giá trị tôi nhận được từ operationXML của tôi là như thế này và có một thuộc tính xmlns không cần thiết đang chặn việc deserialization của tôi. Không có thuộc tính đó, mọi thứ đều hoạt động tốt. Sau đây là cách nó trông giống như:

"<StatusDocumentItem xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DataUrl/><LastUpdated>2013-02-01T12:35:29.9517061Z</LastUpdated><Message>Job put in queue</Message><State>0</State><StateName>Waiting to be processed</StateName></StatusDocumentItem>" 
+1

"operationXML chứa chuỗi" - phải không? Bạn đã thực sự kiểm tra với, nói, một trình gỡ lỗi? "getJSON" để lấy XML trông có vẻ cá. –

+1

Nếu bạn đặt ví dụ xml thành _operationXML_. Các deserialization hoạt động hoàn hảo tốt. –

+0

Có nó chứa chuỗi, đây là những gì tôi nhận được từ trình gỡ lỗi: " 2013-02-01T12: 13: 02.0997071Z Việc xử lý công việc này đã bắt đầu Started" – Disasterkid

Trả lời

50

Hãy thử điều này:

string xml = "<StatusDocumentItem xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DataUrl/><LastUpdated>2013-02-01T12:35:29.9517061Z</LastUpdated><Message>Job put in queue</Message><State>0</State><StateName>Waiting to be processed</StateName></StatusDocumentItem>"; 
var serializer = new XmlSerializer(typeof(StatusDocumentItem)); 
StatusDocumentItem result; 

using (TextReader reader = new StringReader(xml)) 
{ 
    result = (StatusDocumentItem)serializer.Deserialize(reader); 
} 

Console.WriteLine(result.Message); 
Console.ReadKey(); 

Liệu nó hiển thị "việc đưa vào hàng đợi"?

Các vấn đề liên quan