【问题标题】:Build a Custom Serialization as String in System.Xml.Serialization在 System.Xml.Serialization 中将自定义序列化构建为字符串
【发布时间】:2013-06-09 21:43:37
【问题描述】:

大家好,我有 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>

我该怎么做?

【问题讨论】:

  • Test 2:Text 3这是什么xml?
  • 它不是 xml,它是一个字符串。就像我说的是一个字符串。我想将整个类序列化为单个字符串。
  • @那么不要使用OtherInfo这个类,用字符串替换它:)
  • 好的,但是OtherInfo 类有许多与字符串不同的行为。
  • OtherInfo 类的字段可以像字符串一样序列化。但是方法不能扔垃圾。

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


【解决方案1】:

您可以实现IXmlSerializable interface,因此Info1Info2 属性以&lt;Info&gt;Info1:Info2&lt;/Info&gt; 的方式序列化:

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];
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多