如何解决[XmlType(TypeName = "") 没有被序列化 解决方案说明
我有这个类,它的属性是另一个类类型的数组
[XmlRoot(ElementName = "student")]
public class Student
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "email")]
public string Email { get; set; }
[XmlIgnoreAttribute]
public string Department { get; set; }
[XmlElement(ElementName = "topics")]
public Topic[] Topics { get; set; }
}
[XmlType(TypeName = "topic")]
public class Topic
{
[XmlElement(ElementName = "topiccode")]
public string TopicName;
}
当我尝试将其序列化为 XML 时,它弄乱了作为主题代码父级的顶部标记。所以虽然我希望得到这个
<student>
<name>Max Power</name>
<email>test999@email.com</email>
<topics>
<topic>
<topiccode>CAGLENN_17</topiccode>
</topic>
</topics>
</student>
我得到的是省略了 topic
标签
<student>
<name>Max Power</name>
<email>test999@email.com</email>
<topics>
<topiccode>CAGLENN_17</topiccode>
</topics>
</student>
有没有我想使用的不同选项,或者我没有正确设置?
解决方法
解决方案
您需要更改为使用 [XmlArray(ElementName = "topics")]
:
[XmlArray(ElementName = "topics")]
public Topic[] Topics { get; set; }
说明
原因是通过使用 [XmlElement(ElementName = "topics")]
,您告诉序列化程序您不想要包含元素,并且每个条目都应该存在于主对象中。
如果我们添加第二个主题,我们可以看到这一点:
<?xml version="1.0" encoding="utf-16"?>
<student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>Max power</name>
<email>test999@email.com</email>
<topics>
<topiccode>CAGLENN_17</topiccode>
</topics>
<topics>
<topiccode>CAGLENN_18</topiccode>
</topics>
</student>
另一方面,[XmlArray(ElementName = "topics")]
指定包含数组项的元素的名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。