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

Try it online

说明

原因是通过使用 [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")] 指定包含数组项的元素的名称。