.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 XML Version = "1.0" encoding = "UTF -8 "?>
")] 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"
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:>
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);
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"?>