简体   繁体   English

在XML序列化期间跳过类层次结构级别

[英]Skip a class hierarchy level during XML serialization

I want to serialize a class into: 我想将一个类序列化为:

<?xml version="1.0" encoding="utf-8"?>
<documents>
  <document>
    <element />
    ...
  </document>
  ....
</documents>

I have been experimenting with the following class hierarchy: 我一直在尝试以下类层次结构:

public class A
{
    [XmlArrayItem("document")]
    public List<B> documents = new List<B>();
}

public class B
{
    public string id;

    [XmlArray("element")]
    public List<C> elements = new List<C>();
}

public class C
{
    public string name;
    public string value;
}

Unfortunately, what I get is: 不幸的是,我得到的是:

<?xml version="1.0" encoding="utf-8"?>
<A>
  <documents>
    <document>
      <element />
    </document>
  </documents>
</A>

So how do I get rid of "A", ie the type name of the outmost class? 那么如何摆脱“A”,即最外层的类型名称?

A broader question would be, how can this be generalized? 一个更广泛的问题是,如何推广? How can I skip arbitrary "levels" within my class hierarchies during serialization? 如何在序列化期间跳过类层次结构中的任意“级别”?

The outer-most class is called the "root". 最外层的类称为“根”。 You have to use [XmlRoot] to set it. 您必须使用[XmlRoot]进行设置。

However, then you also have to use [XmlElement] on documents instead of [XmlArrayItem] in order to make it the sub-level of the root. 但是,您还必须在文档上使用[XmlElement]而不是[XmlArrayItem],以使其成为根的子级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM