【问题标题】:Deserializing XML from String从字符串反序列化 XML
【发布时间】:2026-02-18 21:05:02
【问题描述】:

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

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

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

【问题讨论】:

  • "operationXML 包含字符串" - 是吗?你真的检查过,比如说,一个调试器吗?检索 XML 的“getJSON”看起来很可疑。
  • 如果您将 xml 示例设置为 operationXML。反序列化效果很好。
  • 是的,它确实包含字符串,这是我从调试器得到的:"w3.org/2001/XMLSchema-instance\">2013-02-01T12: 13:02.0997071Z该任务的处理已经开始1Started"
  • @Pedram string operationXML = "2013-01-31T15:28:13.2847259Z这个任务的处理有开始1开始";
  • @Pedram 我有 result.Message = "Job put in queue".

标签: c# .net xml xml-deserialization


【解决方案1】:

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

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

【讨论】:

  • 最好的方法,imo
【解决方案2】:

试试这个:

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

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

【讨论】:

    最近更新 更多