XML 序列化结构 [英] XML Serialization structure

查看:29
本文介绍了XML 序列化结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉无法更具体地描述标题,但我只能举个例子来解释.

Apologies on not being able to phrase the title more specifically but I can only explain by giving an example.

我正在尝试构建一个序列化为以下 XML 的类

I'm trying to build a class that serializes to the following XML

<Customize>
    <Content></Content>
    <Content></Content>
    <!-- i.e. a list of Content -->

    <Command></Command>
    <Command></Command>
    <Command></Command>
    <!-- i.e. a list of Command -->
</Customize>

我的 C# 是:

[XmlRoot]
public Customize Customize { get; set; }

public class Customize
{
    public List<Content> Content { get; set; }
    public List<Command> Command { get; set; }
}

但是,这会产生(应该如此)以下内容:

However, this produces (as it should), the following:

<Customize>
    <Content>
        <Content></Content>
        <Content></Content>
    </Content>
    <Command>
        <Command></Command>
        <Command></Command>
        <Command></Command>
    </Command>
 </Customize>

是否有一些 xml 序列化属性可以帮助实现我想要的 xml,或者我是否必须找到另一种编写类的方法?

Are there some xml serialization attributes that would help achieve my desired xml, or do I have to find another way to write the class?

推荐答案

使用 XmlElementAttribute 来标记您的集合属性.

Use XmlElementAttribute to mark your collection properties.

public class Customize
{
    [XmlElement("Content")]
    public List<Content> Content { get; set; }

    [XmlElement("Command")]
    public List<Command> Command { get; set; }
}

快速测试代码:

var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } };

string result;

using (var writer = new StringWriter())
{
    var serializer = new XmlSerializer(typeof(Customize));
    serializer.Serialize(writer, item);
    result = writer.ToString();
}

打印:

<?xml version="1.0" encoding="utf-16"?>
<Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Content />
  <Content />
  <Command />
  <Command />
  <Command />
</Customize>

这篇关于XML 序列化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆