日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C#復(fù)雜XML反序列化為實體對象兩種方式小結(jié)_C#教程

作者:追逐時光者 ? 更新時間: 2022-06-04 編程語言

前言

今天主要講的是如何把通過接口獲取到的Xml數(shù)據(jù)轉(zhuǎn)換成(反序列化)我們想要的實體對象,當然Xml反序列化和Json反序列化的方式基本上都是大同小異。都是我們事先定義好對應(yīng)的對應(yīng)的Xml實體模型,不過Xml是通過XmlSerializer類的相關(guān)特性來對實體對象和 XML文檔之間進行序列化和反序列化操作的。序列化和反序列化其實都還好,我們可以調(diào)用封裝好的XmlHelper幫助類即可實現(xiàn),最關(guān)鍵的是我們該如何去定義這些實體模型(Model)。當你遇到對方接口一下子返回一大串的Xml數(shù)據(jù)并且里面存在很多不同的Xml節(jié)點,你該怎么辦一個一個去解析這些節(jié)點到模型上去嗎?本文我主要講兩種方式,第一種方法是通過手寫的方式去定義Xml的實體對象模型類,第二種方法是通過Visual Studio自帶的生成Xml實體對象模型類。

需要操作的Xml數(shù)據(jù)

注意:以下是我稍微簡化的Xml數(shù)據(jù),實際數(shù)據(jù)可能比這里要復(fù)雜個大幾倍。



    
successfuly 20211216081218

一、通過是手寫的方式去定義Xml的實體對象模型類

當然假如你有耐心、時間充足并且眼睛好的話可以使用這種手寫的方式去定義,很多情況寫到最好都會把自己給寫糊涂了(可能是我年紀大了的原因)。

namespace Practices.Models
{
    /// 
    /// Envelope
    /// 
    [XmlType(TypeName = "envelope")]
    public class CityDataModel
    {
        /// 
        /// header
        /// 
        [XmlElement("header")]
        public Header header { get; set; }

        /// 
        /// response
        /// 
        [XmlElement("response")]
        public Response response { get; set; }

    }

    /// 
    /// Header
    /// 
    [XmlType(TypeName = "header")]
    public class Header
    {
        /// 
        /// version
        /// 
        [XmlElement("version")]
        public Version version { get; set; }

        /// 
        /// timestamp
        /// 
        [XmlElement("timestamp")]
        public string timestamp { get; set; }
    }

    /// 
    /// Version
    /// 
    public class Version
    {
        /// 
        /// port
        /// 
        [XmlAttribute("port")]
        public string port { get; set; }

        /// 
        /// host
        /// 
        [XmlAttribute("host")]
        public string host { get; set; }

        /// 
        /// value:XmlTextAttribute指示該屬性作為XML文本處理
        /// 
        [XmlTextAttribute()]
        public string value { get; set; }

    }

    /// 
    /// Response
    /// 
    [XmlType(TypeName = "response")]
    public class Response
    {
        /// 
        /// type
        /// 
        [XmlAttribute]
        public string type { get; set; }

        /// 
        /// product
        /// 
        [XmlAttribute]
        public string product { get; set; }

        /// 
        /// cities
        /// 
        [XmlArray("cities")]
        public List cities { get; set; }

    }

    /// 
    /// class: City
    /// 
    [XmlType(TypeName = "city")]
    public class City
    {
        /// 
        /// code
        /// 
        [XmlElement("code")]
        public Code code { get; set; }

        /// 
        /// city_tax
        /// 
        [XmlElement("city_tax")]
        public City_tax city_tax { get; set; }

        /// 
        /// names
        /// 
        [XmlArray("names")]
        public List names { get; set; }
    }

    /// 
    /// class: Code
    /// 
    [XmlType(TypeName = "code")]
    public class Code
    {
        /// 
        /// 
        /// 
        [XmlAttribute("value")]
        public string value { get; set; }

    }


    /// 
    /// class: City_tax
    /// 
    [XmlType(TypeName = "city_tax")]
    public class City_tax
    {
        /// 
        /// 
        /// 
        [XmlAttribute("value")]
        public string value { get; set; }

    }

    /// 
    /// class: Name
    /// 
    [XmlType(TypeName = "name")]
    public class Name
    {
        /// 
        /// 
        /// 
        [XmlAttribute("language")]
        public string language { get; set; }

        /// 
        /// 
        /// 
        [XmlAttribute("value")]
        public string value { get; set; }

    }
}

二、通過Visual Studio自帶的生成Xml實體對象模型類

Vs被稱為宇宙最強IDE也不是沒有理由的,它集成了很多自動創(chuàng)建功能,如自動生成Json類、Xml類等,雖然說使用Vs自動生成的Xml模型可讀性有點差并且有些冗余,但是快捷省事,只需要略微改動一下即可使用。

1、首先Ctrl+C復(fù)制你需要生成的Xml文檔內(nèi)容

2、找到編輯=》選擇性粘貼=》將Xml粘貼為類

3、以下是使用VS自動生成的Xml類

namespace Practices.Models
{

    // 注意: 生成的代碼可能至少需要 .NET Framework 4.5 或 .NET Core/Standard 2.0。
    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    //TODO:注意這里因為我把類名改成了我自定義的,所以在TypeName這里需要聲明Xml文檔的節(jié)點名
    [System.Xml.Serialization.XmlTypeAttribute(typeName: "envelope")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class NewCityDataModel
    {

        private envelopeHeader headerField;

        private envelopeResponse responseField;

        /// 
        public envelopeHeader header
        {
            get
            {
                return this.headerField;
            }
            set
            {
                this.headerField = value;
            }
        }

        /// 
        public envelopeResponse response
        {
            get
            {
                return this.responseField;
            }
            set
            {
                this.responseField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeHeader
    {

        private envelopeHeaderVersion versionField;

        private ulong timestampField;

        /// 
        public envelopeHeaderVersion version
        {
            get
            {
                return this.versionField;
            }
            set
            {
                this.versionField = value;
            }
        }

        /// 
        public ulong timestamp
        {
            get
            {
                return this.timestampField;
            }
            set
            {
                this.timestampField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeHeaderVersion
    {

        private ushort portField;

        private string hostField;

        private string valueField;

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public ushort port
        {
            get
            {
                return this.portField;
            }
            set
            {
                this.portField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string host
        {
            get
            {
                return this.hostField;
            }
            set
            {
                this.hostField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeResponse
    {

        private envelopeResponseCity[] citiesField;

        private string typeField;

        private string productField;

        /// 
        [System.Xml.Serialization.XmlArrayItemAttribute("city", IsNullable = false)]
        public envelopeResponseCity[] cities
        {
            get
            {
                return this.citiesField;
            }
            set
            {
                this.citiesField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string product
        {
            get
            {
                return this.productField;
            }
            set
            {
                this.productField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeResponseCity
    {

        private envelopeResponseCityCode codeField;

        private envelopeResponseCityCity_tax city_taxField;

        private envelopeResponseCityName[] namesField;

        /// 
        public envelopeResponseCityCode code
        {
            get
            {
                return this.codeField;
            }
            set
            {
                this.codeField = value;
            }
        }

        /// 
        public envelopeResponseCityCity_tax city_tax
        {
            get
            {
                return this.city_taxField;
            }
            set
            {
                this.city_taxField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlArrayItemAttribute("name", IsNullable = false)]
        public envelopeResponseCityName[] names
        {
            get
            {
                return this.namesField;
            }
            set
            {
                this.namesField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeResponseCityCode
    {

        private string valueField;

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeResponseCityCity_tax
    {

        private bool valueField;

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public bool value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

    /// 
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class envelopeResponseCityName
    {

        private string languageField;

        private string valueField;

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string language
        {
            get
            {
                return this.languageField;
            }
            set
            {
                this.languageField = value;
            }
        }

        /// 
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }



}

驗證兩個Xml類是否能夠反序列化成功

///      
        /// 讀取Xml文件內(nèi)容反序列化為指定的對象  
        ///     
        /// Xml文件的位置(絕對路徑)  
        ///     
        public static T DeserializeFromXml(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    throw new ArgumentNullException(filePath + " not Exists");
                using (StreamReader reader = new StreamReader(filePath))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

C# XML基礎(chǔ)入門(XML文件內(nèi)容增刪改查清)

https://www.jb51.net/article/243168.htm

C#XmlHelper幫助類操作Xml文檔的通用方法匯總

https://www.jb51.net/article/242389.htm

.NET中XML序列化和反序列化常用類和用來控制XML序列化的屬性總結(jié)

https://www.jb51.net/article/243165.htm

原文鏈接:https://www.cnblogs.com/Can-daydayup/p/16036890.html