The deserialization of XML can be insinuate by tagging attributes on the properties of the class. For example, this form
Public classPaymentaccount {[XmlAttribute ("name")] Public stringName {Get;Set; } [XmlAttribute ("Environment")] Public stringEnvironment {Get;Set; } [XmlElement ("WebServiceURL")] Public stringWebServiceURL {Get; Set; } [XmlElement ("Websiteurl")] Public stringWEBURL {Get; Set; } [XmlArray ("Paymenttypes")] [XmlArrayItem ("Paymenttype",typeof(Paymenttype))] PublicList<paymenttype> Paymenttypes {Get;Set; } }
You can also implement IXmlSerializable to implement custom serialization and deserialization
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Xml;usingSystem.IO;usingSystem.Xml.Serialization;namespacemvctest{[XmlRoot ("SiteMap", Namespace =NameSpace)] Public classsitemapconfig:ixmlserializable {Private Const stringNameSpace ="Urn:schemas-test-com:sitemap"; Public Staticsitemapconfig Instance {Get{sitemapconfig CG=NULL; stringPath = HttpContext.Current.Server.MapPath ("~/config/sitemap.config"); using(FileStream fs =NewFileStream (path, FileMode.Open)) {XmlSerializer xs=NewXmlSerializer (typeof(Sitemapconfig)); Objectobj=XS. Deserialize (FS); CG=(sitemapconfig) obj; } returnCG; } } PublicSiteMapNode ParentNode {Get;Set; } PublicSystem.Xml.Schema.XmlSchema GetSchema () {return NULL; } Public voidReadXml (XmlReader reader) {XmlDocument doc=NewXmlDocument (); Doc. Load (reader); XmlNamespaceManager xn=NewXmlNamespaceManager (Doc. NameTable); Xn. AddNamespace ("SM", NameSpace); XmlNode Pnode= Doc. selectSingleNode ("/sm:sitemap/sm:sitemapnode", xn); ParentNode=NewSiteMapNode () {Children=NewList<sitemapnode>(), Description= pnode.attributes["Description"]. Value, Title=pnode.attributes["title"]. Value, Url= pnode.attributes["URL"]. Value}; XmlNodeList List=Pnode.childnodes; Readnodes (parentnode, list); } Private voidreadnodes (SiteMapNode pnode, XmlNodeList nList) {if(nlist==NULL|| Nlist.count = =0) { return; } Pnode.children=NewList<sitemapnode>(); foreach(XmlNode nodeinchnList) {SiteMapNode SNode=NewSiteMapNode () {Parent=Pnode, Description= node. attributes["Description"]. Value, Title= node. attributes["title"]. Value, Url= node. attributes["URL"]. Value}; PNODE.CHILDREN.ADD (SNode); Readnodes (SNode, node. ChildNodes); } } Public voidWriteXml (XmlWriter writer) {}} Public classSiteMapNode { PublicSiteMapNode Parent {Get;Set; } Public stringURL {Get;Set; } Public stringTitle {Get;Set; } Public stringDescription {Get;Set; } PublicList<sitemapnode> Children {Get;Set; } }}
XML file:
<?xml version="1.0"encoding="Utf-8"? ><sitemap xmlns="Urn:schemas-test-com:sitemap"> <sitemapnode url=""title="P1"description=""> <sitemapnode url=""title="C1"description=""/> <sitemapnode url=""title="C2"description=""/> </siteMapNode></siteMap>
Deserialization of XML