代码之家  ›  专栏  ›  技术社区  ›  Pakman

将类的ToString()值序列化为XmlElement

  •  6
  • Pakman  · 技术社区  · 15 年前

    [Serializable]
    public ClassA 
    {
        [XmlElement]
        public string PropertyA { get; set; } // works fine
    
        [XmlElement]
        public ClassB MyClassB { get; set; }
    }
    
    [Serializable]
    public ClassB
    {
        private string _value;
    
        public override string ToString()
        {
            return _value;
        }
    }
    

    <PropertyA>Value</PropertyA>
    <ClassB />
    

    相反,我希望它是:

    <PropertyA>Value</PropertyA>
    <ClassB>Test</ClassB>
    

    …假设 _value == "Test" 提供B类公共财产 _value ? 谢谢!

    通过在类B中实现IXmlSerializable接口( shown here

    <PropertyA>Value</PropertyA>
    <ClassB>
        <Value>Test</Value>
    </ClassB>
    

    这个解决方案几乎可以接受,但最好去掉标记。有什么想法吗?

    2 回复  |  直到 15 年前
        1
  •  4
  •   Peter    15 年前

    正如您所指出的,唯一的方法是实现IXmlSerializable接口。

    public class ClassB : IXmlSerializable
    {
        private string _value;
    
        public string Value {
            get { return _value; }
            set { _value = value; }
        }
    
        public override string ToString()
        {
            return _value;
        }
    
        #region IXmlSerializable Members
    
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
    
        public void ReadXml(System.Xml.XmlReader reader)
        {
            _value = reader.ReadString();
        }
    
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteString(_value);
        }
    
        #endregion
    }
    

    正在序列化以下实例。。。

    ClassB classB = new ClassB() { Value = "this class's value" };
    

    将返回以下xml:

    <?xml version="1.0" encoding="utf-16"?><ClassB>this class's value</ClassB>
    

    您可能需要进行一些验证,以便对xml标记等进行编码。

        2
  •  3
  •   itsho    15 年前

    如果从IXmlSerializable派生,则可以更改方法以完全(希望)执行您希望的操作:

        public void WriteXml(System.Xml.XmlWriter writer)
        {
             writer.WriteElementString("ClassB",_value);
        }