網(wǎng)站首頁 編程語言 正文
前言
今天主要講的是如何把通過接口獲取到的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 Listcities { 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 Listnames { 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
相關(guān)推薦
- 2022-01-17 在日常前端開發(fā)工作中,需要養(yǎng)成哪些比較好的習(xí)慣
- 2022-12-13 Android?Loop機制中Looper與handler詳細分析_Android
- 2022-02-22 電腦鍵盤注冊表已損壞導(dǎo)致無法輸入信息的修復(fù)方式
- 2022-07-26 用3dmax做折扇的思路方法與步驟
- 2024-03-20 錯誤code128:npm ERR! An unknown git error occurred c
- 2023-11-20 Linux、jetson nano、JTX、英偉達、nVidia查看cuda版本
- 2022-05-01 C語言實現(xiàn)學(xué)籍管理系統(tǒng)_C 語言
- 2022-06-07 C++實現(xiàn)關(guān)系與關(guān)系矩陣的代碼詳解_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支