序列化自定义数据类型

时间:2019-06-12 06:31:23

标签: xml serialization xsd

[
    {
        "Item Type": "Snacks",
        "Year_Month": "Jul-2017",
        "Total Cost": 4500,
        "Diff": "5"
    },
    {
        "Item Type": "Chocolates",
        "Year_Month": "Jul-2017",
        "Total Cost": 3000,
        "Diff": "4"
    },
    {
        "Item Type": "Ice Cream",
        "Year_Month": "Jul-2017",
        "Total Cost": 4000,
        "Diff": "Nan"
    }
]

当我创建class对象并分配值时,我现在将XSD转换为c#Class

  

无法将类型'int'隐式转换为'Frameworkgo.Envelope.IdentifierType

我正在进行序列化,请帮忙

谢谢

1 个答案:

答案 0 :(得分:0)

运行并测试100%。

using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ObjectEnvelopeType objectenvelopetype = new ObjectEnvelopeType();
            objectenvelopetype.DocumentReference = new ReferenceType();
            objectenvelopetype.DocumentReference.DocumentID = 345;

            XmlSerializer serializer = new XmlSerializer(typeof(ObjectEnvelopeType));
            FileStream fs = new FileStream("Object.xml", FileMode.Create);
            serializer.Serialize(fs, objectenvelopetype);
            fs.Close();

            Console.ReadKey();
        }
    }

    public partial class ObjectEnvelopeType
    {
        private ReferenceType documentReferenceField;
        public ReferenceType DocumentReference { get { return this.documentReferenceField; } set { documentReferenceField = value; } }
    }

    public partial class ReferenceType
    {
        private int documentIDField;
        public int DocumentID { get { return documentIDField; } set { documentIDField = value; } }
    }
    public partial class DocumentReferenceType
    {
        private IdentifierType idField;
        public IdentifierType ID { get { return this.idField; } set { this.idField = value; } }
    }
    public partial class IdentifierType
    {
        private string identificationSchemeIDField;
        [System.Xml.Serialization.XmlAttributeAttribute(DataType = "normalizedString")]
        public string identificationSchemeID { get { return this.identificationSchemeIDField; } set { this.identificationSchemeIDField = value; } }
    }
}