从字符串反序列化的XML(Deserializing XML from String)

2019-07-19 03:30发布

我想,结果我从我的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;
}

这是如何我试图让该字符串类型StatusDocumentItem的对象与XMLDeserializer(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>"

Answer 1:

试试这个:

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

这是否显示“工作放在队列”?



Answer 2:

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


文章来源: Deserializing XML from String