将类序列化为单个无属性元素,并将其内容设置为一个属性

时间:2012-01-18 22:07:38

标签: .net xml xml-serialization xmlserializer serializable

我想序列化/反序列化以下类型:

// The "NameEntity" element shouldn't appear in the XML
public class NameEntity
{
    [XmlElement("name")]
    public string Name { get; set; }
}

[XmlRoot("names")]
public class Names : List<NameEntity>
{
}

我希望序列化的XML符合以下方案:

<?xml version="1.0" encoding="utf-8" ?>
<names>
  <name>Charlie</name>
  <name>Robert</name>
  <name>Nick</name>
</names>

实际上,输出XML是:

<names>
  <NameEntity>
    <name>Charlie</name>
  </NameEntity>
  ...
</names>

这是否可以使用.NET中的某个XML属性,或者我必须实现IXmlSerializable

1 个答案:

答案 0 :(得分:2)

您需要XmlType AttributeXmlText Attribute混合使用...

// The "NameEntity" element shouldn't appear in the XML
[XmlType("name")]
public class NameEntity
{
    [XmlText]
    public string Name { get; set; }
}

[XmlRoot("names")]
public class Names : List<NameEntity>
{
}

public class SO
{
    [Test]
    public void NameEntitySerialization()
    {
        var name = new NameEntity() { Name = "Austin" };

        var serialized = <YOUR SERIALIZATION CODE HERE>
        Console.WriteLine(serialized);
        Assert.AreEqual("<name>Austin</name>", serialized);
    }

    [Test]
    public void ListSerialization()
    {
        var names = new Names();
        names.Add(new NameEntity() {Name = "Austin"});

        var serialized = <YOUR SERIALIZATION CODE HERE>
        Console.WriteLine(serialized);
        Assert.AreEqual("<names>\r\n  <name>Austin</name>\r\n</names>",
          serialized);
    }
}