繁体   English   中英

如何将 class 序列化为字符串?

[英]How do I serialize a class to a string?

如何序列化组织类型 class? 没有其他属性 - 包装器。

public class INNType : IConvertToString
{
    protected INNType() { }

    public string Value { get; }

    public INNType(string inn)
    {
        if (!Regex.IsMatch(inn, @"^\d{10}$")) throw new Exception(@"");
        Value = inn;
    }
    public override string ToString() => Value;
    public static implicit operator INNType(string inn) => new INNType(inn);
    public static implicit operator string(INNType inn) => inn?.Value;        
}

[Serializable]
[XmlType(Namespace = "http://roskazna.ru/gisgmp/xsd/Organization/2.2.0")]
public class OrganizationType
{
    protected OrganizationType() {}

    [XmlAttribute("inn")]
    public INNType Inn {get; set;}
}

序列化后,它应该如下所示。

<OrganizationType inn="1234567890"  />

用于序列化对象的方法如下所示

public static XmlDocument SerializerObject<T>(T obj, XmlSerializerNamespaces xsn) where T : class
{
    XmlDocument xmlDocument = new XmlDocument();

    using (var xs = xmlDocument.CreateNavigator().AppendChild())
    {
        new XmlSerializer(typeof(T)).Serialize(xs, obj, xsn);
    }
    return xmlDocument;
}

例外

System.InvalidOperationException : Cannot serialize member 'Inn' of type GisGmp.INNType. XmlAttribute/XmlText cannot be used to encode complex types.

我必须这样做。 不好。

[XmlIgnore]
public INNType Inn {get; set;}

[XmlAttribute("inn")]
public string WrapperInn { get => Inn; set => Inn = value; }

您可以实现IXmlSerializable

    [Serializable]
    public class OrganizationType : IXmlSerializable
    {
        public OrganizationType()
        {
            // Demo
            this.Inn = new INNType("0123456789");
        }

        [XmlAttribute("inn")]
        public INNType Inn { get; set; }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            return;
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("inn", this.Inn.Value);
        }
    }

Output:

<OrganizationType inn="0123456789" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM