0xFF
0xFF

Reputation: 49

How do I serialize a class to a string?

How to serialize the OrganizationType class? No additional properties - wrappers.

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

After serialization, it should look like below.

<OrganizationType inn="1234567890"  />

The method used to serialize objects looks like this

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

Exception

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

I have to do it. Not good.

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

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

Upvotes: 2

Views: 210

Answers (1)

Saber
Saber

Reputation: 501

You could implement 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" />

Upvotes: 2

Related Questions