44

我正在尝试将从我的 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 类型的对象的方式(注意,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>"
4

2 回答 2

118

试试这个:

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

它是否显示“作业已排队”?

于 2013-02-01T12:45:26.043 回答
3

这个通用扩展对我很有效....

public static class XmlHelper
{
    public static T FromXml<T>(this string value)
    {
        using TextReader reader = new StringReader(value);
        return (T) new XmlSerializer(typeof(T)).Deserialize(reader);
    }
}
于 2021-10-14T03:22:15.453 回答