c# - 无法反序列化 XML

标签 c# xml xml-deserialization

我正在尝试反序列化以下 XML:

<?xml version="1.0" encoding="UTF-8"?>
<jobInfo
xmlns="http://www.force.com/2009/06/asyncapi/dataload">
<id>750x0000000005LAAQ</id>
<operation>insert</operation>
<object>Contact</object>
<createdById>005x0000000wPWdAAM</createdById>
<createdDate>2009-09-01T16:42:46.000Z</createdDate>
<systemModstamp>2009-09-01T16:42:46.000Z</systemModstamp>
<state>Open</state>
<concurrencyMode>Parallel</concurrencyMode>
<contentType>CSV</contentType>
<numberBatchesQueued>0</numberBatchesQueued>
<numberBatchesInProgress>0</numberBatchesInProgress>
<numberBatchesCompleted>0</numberBatchesCompleted>
<numberBatchesFailed>0</numberBatchesFailed>
<numberBatchesTotal>0</numberBatchesTotal>
<numberRecordsProcessed>0</numberRecordsProcessed>
<numberRetries>0</numberRetries>
<apiVersion>28.0</apiVersion>
</jobInfo>

我创建了这个对象:

public class JobInfo
{
    public string xmlns { get; set; }
    public string id { get; set; }
    public string operation { get; set; }
    public string @object { get; set; }
    public string createdById { get; set; }
    public string createdDate { get; set; }
    public string systemModstamp { get; set; }
    public string state { get; set; }
    public string concurrencyMode { get; set; }
    public string contentType { get; set; }
    public string numberBatchesQueued { get; set; }
    public string numberBatchesInProgress { get; set; }
    public string numberBatchesCompleted { get; set; }
    public string numberBatchesFailed { get; set; }
    public string numberBatchesTotal { get; set; }
    public string numberRecordsProcessed { get; set; }
    public string numberRetries { get; set; }
    public string apiVersion { get; set; }
}

public class RootObject
{
    public JobInfo jobInfo { get; set; }
}

而且,我正在使用这段代码:

XmlSerializer serializer = new XmlSerializer(typeof(RootObject));
StringReader rdr = new StringReader(response);
RootObject resultingMessage = (RootObject)serializer.Deserialize(rdr);

但是,我得到这个错误:

There is an error in XML document (1, 40).

{"<jobInfo xmlns='http://www.force.com/2009/06/asyncapi/dataload'> was not expected."}

我如何解释 xmlns 属性?我的代码将它作为一个属性(因此,它失败了)...

最佳答案

目前您的代码需要 xmlns 作为元素,而不是属性。

您应该添加 XmlSerialization attributes到你的类(class),像这样:

[XmlRoot("jobInfo", Namespace="http://www.force.com/2009/06/asyncapi/dataload"]
public class JobInfo
{
    [XmlAttribute]
    public string xmlns { get; set; }
    [XmlElement(ElementName = "id")]
    public string id { get; set; }
    ....
}

您可以在 MSDN 文章中找到更多信息:

关于c# - 无法反序列化 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889399/

相关文章:

c# - 从 c# 将 rdl 报告导出到多张 excel 文件有问题

php - xml中具有相同名称的多个节点

c# - 反序列化 XMl 错误

c# - 使用泛型 C# 反序列化动态 XML

android - 如何在数据绑定(bind)的 xml 中有空格和特殊字符?

c# - XML反序列化: Same element name but different type

c# - 在 .NET 中创建 XMLSerializer 会引发异常

c# - 在 OpenXml.Wordprocessing 中检测可打印区域宽度

c# - c#.net 中用于 winforms 的气球类

java - fragment 问题中的 NullPointerException