.NET makes XML serialization

xiaoxiao2021-03-06  44

.NET makes XML serialization

People have always yelling XML is the key to resolving system interconnections, and .NET Framework also provides many different class libraries for processing XML data. XMLDocument categories allow you to process XML data like processing files, and XmlReader, Xmlwriter, and them The derived class allows you to make XML data as data stream processing. XMLSerializer provides additional methods that allow you to serve your object serial and reverse serial to XML. Serialized data can make you like Treat files are random access, while you can skip your elements you are not interested. In this article, I will show you how to use the XMLSerializer class and how to add attributes in your class to control the serialization process. The XMLSerializer XMLSerIzer class is in System.xml.dll in System.Xml.Serialization namespace, which provides serialization in a highly loosely coupled manner. Your class does not need to inherit a special base class, and they don't Any special interface is required. Conversely, you only need to add custom properties in your class or these classes of public domains and read / write properties. XMLSerializer reads these properties through the reverse mapping and use them to use them and Class members are mapped to XML elements and properties. Write XML to object considering the XML statement in Table A. Which one correctly describes the movie released in a cinema? Table A The camera> (888) 665-222 The score </ Title> <Rating> R </ Rating> <showing> 16:15:00 </ showing> <showing> 19:05:00 </ showing> <showing> 21:40:00 </ shwing> </ movie> <Movie Minutes = "100"> <title> Shrek </ Title> <Rating> PG-13 </ Rating> <Showing> 16:00:00 </ shwing> < Showing> 19:00:00 </ shwing> <showing> 21:40:00 </ shwing> </ movie> </ theater> Table B defines a THEATER (Cinema) class, which contains the properties used by XMLSerializer mapping table B using System; using System.Xml.Serialization; namespace Articles.TechRepublic.XmlSerialization {[XmlRoot ( "theater")] public class Theater {[XmlElement ( "name")] public string name = ""; [XmlElement ("Phone")] public string phone = ""; [XMLELEMENT ("</p> <p>")] public movie [] movies; public override string toString () {string movies =" "; if (movies! = null) foreach (movie movie in movies) Movies =" / n " movie.toString () Return string.format ("{0} / n {1} / n {2}", name, phone, movies);}} XMLROOT property maps theater to the root element of XML. Xmlelement property will name, Phone And the Movies Data is mapped to Name, Phone, and Movie XML elements nested in the theater element. Because Movies are the MOVIE array, XMLSerializer maps it to multiple XML Movie elements. Table c shows a property with properties Mapping MOVIE Table C Public Class Movie {[XMLELEMENT ("Title")] Public String Title = ""; [Xmlattribute ("Minutes")] Public uint minutes = 0; [XMLELEMENT ("Showing", DataType = "Time ")] public DateTime [] showings; public override string ToString () {string showings =" ";! if (showings = null) {showings =" shows at "; foreach (DateTime showing in showings) showings = showing.ToShortTimeString () ""} Else {showings = "- no showings"; } Return string.format ("{0} ({1} min) {2}", title, minutes, showings;}} XMLELEMENT property maps Title and Showings Data to Title and Showing XML elements in the MOVIE element. Like theater.movie, as the DateTime array Movie.showings is mapped to multiple XML Showing elements. The properties of the Showing Data include location attribute parameters DataType = "Time"</p> <p>It maps the datetime value to an XML time value, which removes the date information and only retains time information. The xmlattribute property maps the Minutes Data to the XML attribute instead of the XML element. XML data in Moviestars (movie) attribute and Rating (Last Rate) Element is not mapped to anything in the Movie class. When the serialization XML data, XMLSerializer is just a simple skipping project that it cannot map. When serializing an object, you can In the public data domain and you want XMLRSerializer skipped in the properties. XMLROOT, XMLELEMENT, and XMLATITRIBUTE The attribute class should include suffix "Attribute." In my properties, I used there to have an abbreviated form without suffix. Public properties in theater and Movie classes can be rewritten into public properties for better encapsulation. XMLSerializer can use them in the same way. I am here as a data domain use to make the code more compact. XML Data Definition into an object to load XML data into a THEATER object. Now it is very easy. The program, XMLIN in Table D, creates a theater object by anti-serialization Movie Showings XML data. This program passes the command line Execute, you need to indicate an entered XML file. Table D use system.xml.Serialization; use system.io; using articles.techrepublic.xmlSerization; public class xmlin {public static void main (string [] args) { IF (args.length! = 1) {console.writeLine ("usage: xmlin infile.xml"); return;} try} try} try} Try {// deserialize the specified file to aate Object. Xmlserializer Xs = New XMLSeriAli ZER (Tyater); filestream fs = new filestream (args [0], filemode.open; theater theater = (theater) xs.deSerialize (fs); // display theate Object. console.writeline (theater) ;} Catch (exception x) {console.writeline ("Exception:" x.Message);}}} Output:></p> <p>Xmlin theaterin.xml the Camelot (888) 665-2222 The score (120 min) shows at 4:15 pm 7:05 PM 9:40 PM Shrek (100 min) shows at 4:00 PM 7:00 PM 9:40 PM's main program code is placed in the TRY code segment of the main function. First create an XMLSerializer object and indicate a System.Type object to tell the object of the object to be created. TypeOf operator returns a THEATER class System.Type object. Then, open a file stream read the input XML file. Call the XMLSerializer's DeSerialIze method and passes the file stream to it. DeserialIze returns a reference to theater object. Theater and the Tostring method in the theater and the Movie object can be You are simply output. To serialize the object to XML. Generate XML data from a THEATER object is equally easy. The program in Table E, XMLout, is serializing a THEATER object into the XML file. This program passes command line, you need to specify the XML file output table E using System;. using System.Xml; using System.Xml.Serialization; using System.IO; using Articles.TechRepublic.XmlSerialization; public class XmlOut {// Returns a populated PUBLIC Object. Public staticate gettheater () {movie movie = new movie (); movie.title = "o Brother, WHERE ART THOU?"; Movie.minutes = 102; movie.showings = new datetime [3]; movie. Showings [0] = New DateTime (2001, 8, 2, 13, 15, 0); movie.showings [1] = new datetime (2001, 8, 2, 16, 30, 0); movie.showings [2] = New DateTime (2001, 8, 2, 19, 55, 0) Theater theater = new theater (); theater.name = "Hollywood Movies 10"; Theater.Phone = "(972) 555-154"; Theater.Movies = New Movie [1]; Theater.Movies [0] = MOVIE Return theater;} public static void main (string [] args) {if (args.length! = 1) {console.writeline ("usage: xmlout outfile.xml); return;} try {THEATER THEATER = GetTheater ); // serialize the theater Object to an Xml file. Xmlserializer XS = New XMLSerializer (Tyater);</p> <p>FileStream Fs = New FileStream (args [0], filemode.create); xs.serialize (fs, theater);} catch (exception x) {console.writeline ("Exception:" x.Message);}}} invocation :> Xmlout theaterout.xml theaterout.xml contents: <? XML version = "1.0"?> <Theater XMLns: XSI = http://www.w3.org/2001/xmlschema-instance XMLns: XSD = "http: / / www.w3.org/2001/xmlschema> <name> Hollywood Movies 10 </ name> <phone> (972) 555-154 </ phone> <movie minutes = "102"> <title> o brother, where Art soing> </ title> <showing> 13: 15: 00.0000000-06: 00 </ shwing> <showing> 16: 30: 00.0000000-06: 00 </ shwing> <showing> 19: 55: 00.0000000-06: 00 </ shwing> </ movie> </ theater> The primary program code is placed in the TRY code segment of the main function. First create a Theater object through the GetTheater Help function. Then, open a file stream to generate an output XML file. Call the XMLSerializer's Serialize method, passed to its file stream and theater object. This is the simple -XML file generation! The product of the output is included in the XML namespace (XMLns) generated for template and template instance namespace, though In these two namespaces, these data do not represent anything. The -06: 00 in the showing element refers to the US ministerial time, or when the GMT time is reduced, it is my time zone. Move number According to a small dish, XMLSerializer makes it easy to move data between objects and XML, as long as the XML mapping attribute is added, but for more complex object models, manually created XML mappings become very troublesome and easy to make mistakes In my next article, I will tell you how to automate this work and achieve more stringent control for your XML data.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-51620.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="51620" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'FuA9hl6k0E_2FhmZ749NzgJ9He5jWUe2eWq5dZIY2lfzsDzuR7P66BZaps8D1HtOMfCoY_2F9LknYGyBNEIu53JNjw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>