从String反序列化XML

时间:2013-02-01 12:08:04

标签: c# .net xml xml-deserialization

我正在尝试将我从Web服务获得的结果转换为字符串并将其转换为对象。

这是我从服务中获得的字符串:

<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>

所以我有一个课程:

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

这就是我试图通过XMLDeserializer将该字符串作为StatusDocumentItem类型的对象(NB。operationXML包含字符串):

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

但我的结果对象总是空的。我做错了什么?

更新即可。我从我的operationXML获得的值是这样的,并且有一个不必要的xmlns属性阻止了我的反序列化。没有这个属性,一切都很好。这是它的样子:

"<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>"

2 个答案:

答案 0 :(得分:66)

试试这个:

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

是否显示“Job into in queue”?

答案 1 :(得分:-1)

            AccountRequest xml = null;
            var serializer = new XmlSerializer(typeof(AccountRequest));
            using (TextReader reader = new StringReader(requestXml))
            {
                xml = (AccountRequest)serializer.Deserialize(reader);
            }