gpt4 book ai didi

c# - 使用 XML 序列化反序列化数组时不期望元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:15:07 27 4
gpt4 key购买 nike

好的。我正在尝试与 Pivotal Tracker API 进行通信,它只返回 XML 格式的数据。我尝试将以下 XML 反序列化到我的域模型中。


<?xml version="1.0" encoding="UTF-8"?>
<stories type="array" count="2" total="2">
<story>
<id type="integer">2909137</id>
<project_id type="integer">68153</project_id>
<story_type>bug</story_type>
<url>http://www.pivotaltracker.com/story/show/2909137</url>
<current_state>unscheduled</current_state>
<description></description>
<name>Test #2</name>
<requested_by>Anthony Shaw</requested_by>
<created_at type="datetime">2010/03/23 20:05:58 EDT</created_at>
<updated_at type="datetime">2010/03/23 20:05:58 EDT</updated_at>
</story>
<story>
<id type="integer">2909135</id>
<project_id type="integer">68153</project_id>
<story_type>feature</story_type>
<url>http://www.pivotaltracker.com/story/show/2909135</url>
<estimate type="integer">-1</estimate>
<current_state>unscheduled</current_state>
<description></description>
<name>Test #1</name>
<requested_by>Anthony Shaw</requested_by>
<created_at type="datetime">2010/03/23 20:05:53 EDT</created_at>
<updated_at type="datetime">2010/03/23 20:05:53 EDT</updated_at>
</story>
</stories>

我的“故事”对象创建如下:


public class story
{
public int id { get; set; }
public int estimate { get; set; }
public int project_id { get; set; }

public string story_type { get; set; }
public string url { get; set; }
public string current_state { get; set; }
public string description { get; set; }
public string name { get; set; }
public string requested_by { get; set; }
public string labels { get; set; }
public string lighthouse_id { get; set; }
public string lighthouse_url { get; set; }
public string owned_by { get; set; }
public string accepted_at { get; set; }
public string created_at { get; set; }

public attachment[] attachments { get; set; }
public note[] notes { get; set; }
}

当我执行我的反序列化代码时,我收到以下异常:


Exception:
There is an error in XML document (2, 2).

Inner Exception:
<stories xmlns=''> was not expected.

我可以很好地反序列化各个故事,我只是不能将这个 xml 反序列化为一个“故事”对象数组

还有我的反序列化代码(value是xml的字符串)


var byteArray = Encoding.ASCII.GetBytes(value);
var stream = new MemoryStream(byteArray);
var deserializedObject = new XmlSerializer(typeof (story[])).Deserialize(stream)

有没有人有什么想法?

最佳答案

让我提供一个更简洁的解决方案。将反序列化设置为如下所示:

var deserializedObject = new XmlSerializer(typeof(story[]), new XmlRootAttribute("stories")).Deserialize(stream);

通过在 XmlSerializer 中指定第二个参数,您可以避免必须 stub 该类。它让序列化程序知道根元素的名称是什么。

为此,表示数组元素类型的类的名称必须与 XML 名称完全匹配,例如class story {} , <story> .您可以通过指定 XmlType 来解决这个问题(无论如何我都会推荐它作为最佳实践):

[XmlType("story")]
public class Story
{
...
}

我更喜欢这样做,因为它让我摆脱了 XML 类型名称的束缚。

关于c# - 使用 XML 序列化反序列化数组时不期望元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2504569/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com