在System.Xml.Serialization中将自定义序列化构建为字符串

时间:2013-06-09 21:43:38

标签: c# .net xml serialization system.xml

大家好我有2个这样的课程:

[XmlRoot("Config")]
public class ConfigClass
{
    [XmlElement("Configuration1")]
    public string Config1 { get; set; }

    [XmlArray("Infos")]
    [XmlArrayItem("Info")]
    public OtherInfo[] OtherInfos { get; set; }
}

public class OtherInfo
{
    public string Info1 { get; set; }
    public string Info2 { get; set; }
}

当我序列化根类时,XML结果如下:

<?xml version="1.0"?>
<Config>
  <Configuration1>Text</Configuration1>
  <Infos>
    <Info>
      <Info1>Test 2</Info1>
      <Info2>Text 3</Info2>
    </Info>
    <Info>
      <Info1>Test 4</Info1>
      <Info2>Text 5</Info2>
    </Info>
  </Infos>
</Config>

但我希望OtherInfo类被序列化为单个字符串,如下所示:

<?xml version="1.0"?>
<Config>
  <Configuration1>Text</Configuration1>
  <Infos>
    <Info>
      Test 2:Text 3
    </Info>
    <Info>
      Test 4:Text 5
    </Info>
  </Infos>
</Config>

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以实施IXmlSerializable interface,因此Info1Info2属性按<Info>Info1:Info2</Info>的方式序列化:

public class OtherInfo: IXmlSerializable
{
    public string Info1 { get; set; }
    public string Info2 { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        var content = reader.ReadElementContentAsString();

        if (String.IsNullOrWhiteSpace(content))
            return;

        var infos = content.Split(':');
        if (infos.Length < 2)
            return;

        this.Info1 = infos[0];
        this.Info2 = infos[1];
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteString(String.Format("{0}:{1}", this.Info1, this.Info2));
    }
}

如果在应用程序内部还需要格式为“Info1:Info2”的属性,而不仅仅是Xml序列化,那么您可以在OtherInfo中拥有如下所示的属性,并隐藏Info1和Info2。序列:

public class OtherInfo
{
    [XmlIgnore]
    public string Info1 { get; set; }
    [XmlIgnore]
    public string Info2 { get; set; }

    [XmlText]
    public string InfoString
    {
        get
        {
            return String.Format("{0}:{1}", this.Info1, this.Info2);
        }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
                return;

            var infos = value.Split(':');
            if (infos.Length < 2)
                return;

            this.Info1 = infos[0];
            this.Info2 = infos[1];
        }
    }
}