0

タイトルをより具体的に表現できないことをお詫びしますが、例を挙げて説明することしかできません.

次の 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; }
}

ただし、これにより、(当然のことながら) 次の結果が生成されます。

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

目的の xml を実現するのに役立つ xml シリアル化属性がいくつかありますか、それともクラスを記述する別の方法を見つける必要がありますか?

4

2 に答える 2

2

XmlElementAttributeコレクションのプロパティをマークするために使用します。

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>
于 2013-11-05T01:41:26.667 に答える
1
public class Customize
{
    [XmlElement("Content")]
    public List<Content> Content { get; set; }

    [XmlElement("Command")]
    public List<Command> Command { get; set; }
}
于 2013-11-05T01:40:33.560 に答える