The best practices that represent XML in .NET Framework

xiaoxiao2021-03-06  45

The best practices for XML in .NET Framework: Dare Obasanjo is eye-catching with an option that can be shared between components within a single process and an appdomain, and discussing each method in design Pros and cons. Introduction After recent design review, a position is a project manager's colleague asking if there is design guidelines when public XML is disclosed in the API, because he has seen many different methods, but it is impossible to determine what method of the choice. I told him that I was originally believed to find some guidelines on the MSDN, but when I gave it, I only found a piece of MSDN TV titled Passing XML Data Inside The CLR (English), although it contains such information, it is not easy. read. So I sprout such a thought, providing a version of the MSDN TV fragment of Don Box, and provides some experience in Microsoft to process XML APIs. Back to Templicity In the three main cases, developers need to consider using what API to represent XML. The following is a brief introduction to these circumstances and guidelines: XML in the field or property of the class: If the field or attribute is an XML document or segment, the class should provide a mechanism that operates its properties simultaneously as a string and XMLReader. The method can accept XML input or return XML as an output: method of accepting or returning XML should help return XMLReader or XPathnavigator unless the user wants to edit XML data (this clock should be used. Convert objects into XML: If the object is used to represent its own use of XML, the XML serialization process control is more than the XMLSERIALIZER, and XMLWriter should be used. If the object is to indicate itself in XML, it is possible to participate in the identity of XML world members (if XPath query or XSLT conversion is allowed on this object), this object should implement the IXPathnavigable interface. In the parties below, I introduced the few situations mentioned above and explained how I got these guidelines. Back to top Common doubts When you decide to use methods or properties, you will appear in the .NET Framework in your brain, and they apply to this task. The following is listed below, and five classes that are best suited to represent XML inputs or outputs are given in the .NET Framework, and given a brief description of its positive opposition. 1. System.xml.xmlreader (English): XmlReader is the Plus-mode XML Analysis program for .NET Framework. During the pull model processing, the XML user controls the program stream by requesting an event from an XML manufacturer as needed. The pull-type XML analysis program (such as XMLReader) operates with only flow mode while only displaying information about a single node at any given time. In fact, XmlReader does not require the entire XML document to load into memory and is read-only, which makes it a good choice for creating an XML appearance in non-XML data sources. An example of creating an XML appearance in non-XML data sources is XMLCSVReader (English). Some people may regard XmlReader's only characteristics as a limitations because it cannot be passed multiple times by using each part of the XML document.

2. System.xml.xpath.xpathnavigator (English): XPathnavigator is a read-only cursor on the XML data source. The XML cursor is like a lens, focusing on an XML node at a time, but is different from the pull-based API (such as XmlReader), which can position the cursor at any location of the XML document at any given time. To a certain extent, the pull-up API is the only version of the cursor model. XPathnavigator is a good candidate for XML appearance in non-XML data because it allows you to construct an XML view of the data source in real time without having to convert the entire data source into an XML tree. An example of an XML view using XPathnavigator to create non-XML data is Objectxpathnavigator (English). In fact, Xpathnavigator is read-only and lacks some user-friendly properties (such as InnerXML (English) and OuterXML (English)), which makes it impossible to use XMLDocument or XMLNode when needed. 3. System.xml.xmlwriter (English): XMLWRITER provides general mechanisms that push XML documents into basic storage areas. The basic storage area can be from a file (if using xmlTextWriter) to XMLDocument (if you are using XMLNodeWriter (English)) anything. The parameters using XMLWRITER as a way to return XML provide a reliable way to support various possible return types (including file streams, strings, and xmldocument instances). That's why XMLSerializer.Serialize () Method accepts XMLWriter as a parameter on one of the overloads. As the meaning of its name, XMLWriter is only useful to write XML, and cannot be used to read or process XML. 4. System.xml.xmldocument / XMLNode (English): XMLDocument is the implementation of W3C Document Object Model (DOM) (English). The DOM is a representation of the XML document configured by the layered tree of the XMLNode object, which represents the logical components of the XML document, such as elements, attributes, and text nodes. The DOM is the most popular API of XML in the .NET Framework, as it provides a direct method to load, process, and save XML documents. The main defect of the DOM is that its design needs to load the entire XML document into memory. 5. System.String (English): XML is a text-based format and is better than the String class. The main advantage of using a string as an XML representation is that the string is the least blended mother. The string is easy to write to the log file or print it to the console, and if you want to use the XML API to actually handle the XML, you can load the string into XMLDocument or XPathDocument. Use strings as several issues in the main input or output of methods or attributes using XML. The first problem using the string is similar to the DOM, which requires loading the entire XML document into memory.

Second, in a string, XML will increase the burden of the manufacturer to generate an XML string, in some cases, this may be very troublesome. An example that generates an XML string may be very troublesome to get XML from XMLReader or XPathnavigator. Third, the string represents XML may result in confusion related to character encoding, as what code declaration is placed in XML, the string in .NET Framework is always UTF-16 character encoding. Finally, the XML is represented by a string so that the XML processing pipe is difficult because each layer in the pipe must reassure the document. Back to Top Fields or Properties containing XML In some cases, the field or attribute of an object may be an XML document or an XML fragment. The following example class represents an e-mail, its content is XHTML. The XML content of the message is represented by a string and is disclosed by the BODY attribute of the class: public class email {private string from; public string from {get {return from {get {ram = value;}}. public string to {get {return to;} set {to = value;}} private string subject; public string Subject {get {return subject;} set {subject = value;}} private DateTime sent; public DateTime Sent {get { return sent;} set {sent = value;}} private XmlDocument body = new XmlDocument (); public string body {get {return body.OuterXml;} set {body.Load (new System.IO.StringReader (value)); }}} The main representation of the field or attribute that represents the XML document is the most user-friendly representation method because the System.String class is the most familiar XML "common doubt" that general developers. However, this will increase the burden of the user using this class, which may now have to deal with the cost of analyzing the XML document twice. For example, an idea is intended: such an attribute is set in XML obtained from SQLCommand.executexmlReader () Method (English) or XSLTRRANSFORM.TRANSFORM () Method (English).

In this case, the user will have to analyze the document twice, as shown in the following example: email email = new email (); email.From = "Dareo@example.com"; email.to = "michealb@example.org" Email.subject = "Hello World"; xsltransform transform = new xsltransform (); Transform.Load ("format-body.xsl"); xmlDocument body = new xmldocument (); // 1. XML by xmlDocument.Load () Analyze Body.Load (Transform.Transform ("Body.xml"), NULL); // 2. The same xml is again analyzed in the XMLDocument.Load () in the email.body property. Email.Body = body.outerXML In the above example, the same XML is analyzed twice, since the XMLReader must be loaded into the XMLDocument before converting the XML into a string, and then use the XML to set the body of the Email class, then the property itself The XML is analyzed from the inside to XMLDocument. A very effective manner is to provide access to XML properties (as XmlReader and strings). Therefore, the following methods should also be added to the Email class to make the user get the user's maximum flexibility: public void setbody (XmlReader Reader) {body.load (reader);} public xmlreader getBody () {Return New XMLNodeReader This provides a way for users of the Email class that allows these users to deliver, set, and retrieve XML data in a valid manner when needed. Criterion If the field or attribute of the class is an XML document or a clip, the class should provide a mechanism to operate its properties simultaneously as a string and XmlReader. A keen reader may notice that if you disclose XMLDocument directly, you should meet the criteria, and the user should make the user to exact XML. Back to top Method Accepting XML input or returning XML as an output When designing or using XML method, developers have a responsibility to make such a method flexibility when receiving input. When the method accepts XML as an input, you can divide these methods into methods requiring data to modify the data in place, and simply use only read-only access to XML. The only "XML Common Dosage" supporting read and write is XMLDocument.

The following code example shows such a method: public void applydiscount (XmLDocument price) {foreach (xmlelement price in price.selectnodes) {price.innertext = (double.Parse (price.innerText) * 0.85 ) .Tostring ();}} There are two main options for read-only access to XML. XmlReader? Xpathnavigator XmlReader provides only access to XML, and XPathnavigator not only provides random for basic XML sources Access, also provides the ability to perform XPath queries for the data source.

The following code example will print Artist (artist) and Title in the XML document below: 16.95 NELLY Nellyville < / title> </ compact-disc> <compact-disc> <price> 17.55 </ price> <artist> baby d </ artist> <title> lil chopper toy </ title> </ compact-disc> </ items > XmlReader: Public Static Void PrintArtistandPrice (XmlReader Reader) {reader.movetoContent (); //move from root node to document element (items) / * Keep read until you get the first <Artist> element * / while (Reader) .Read ()) {if ((Reader.NodeType == XMLNodType.element) && readype.equals ("artist")) {artist = reader.readElementstring (); title = reader.readElementstring (); break;} } Console.WriteLine ( "Artist = {0}, title = {1}", artist, title);}} XPathNavigator: public static void PrintArtistAndPrice (XPathNavigator nav) {XPathNodeIterator iterator = nav.Select ( "/ items / compact- DISC [1] / artist | / items / compact-disc [1] / title "); item.move Next (); console.writeline ("artist = {0}", item.current); item.movenext (); console.writeline ("Title = {0}", item.current);} Usually returns to XML Methods use similar rules. If you want the recipient to edit XML, you should return XMLDocument. Otherwise, it should be returned to XMLReader or XPathnavigator based on whether only only flowing access to XML data is required. The method accepting or returning XML should help return XMLReader or XPathnavigator unless the user wants to edit XML data (this clock should be used. The above guidelines means that the way to return XML should help return XMLReader because it applies more to more users than any other type.</p> <p>In addition, when the modem needs to more function, they can load XMLDocument or XPathDocument from the returned XMLReader. Back to top Uncommonly converted to XML XML as an information exchange, which makes it an obvious option to indicate some objects of itself with XML, these objects or serialized destination, or for obtaining Access to other XML technology (such as querying or using XSLT using XPATH). When converting objects into XML for serialization, it is clear that the XML Serialization Technology in The .NET Framework (English) should be selected. However, in some cases, your control required to generate the XML may be more than XMLSerializer. In this case, the XMLWRITER in the kit is a very useful class because it makes you no longer need the structure of the structure and a one-to-one map between the generated XML. The following example shows the XML generated by using the XMLWRITER serialization Email class (previously mentioned in the previous sections).</p> <p>public void Save (XmlWriter writer) {writer.WriteStartDocument (); writer.WriteStartElement ( "email"); writer.WriteStartElement ( "headers"); writer.WriteStartElement ( "header"); writer.WriteElementString ( "name", " TO "); Writer.writeElementsTRING (" Value ", this.to); Writer.WriteEndelement (); // Titler Writer.writestartElement (" header "); Writer.writeElementString (" name "," from "); Writer. WriteElementString ("Value", this.from); Writer.WriteEndelement (); // Title Writer.writeStartElement ("header"); Writer.writeElementstring ("name", "Subject"); Writer.writeElementstring ("Value", This.Subject); Writer.WriteEndelement (); // Title Writer.WriteStartElement ("header"); Writer.writeElementString ("name", "SENT"); Writer.writeElementstring ("Value", XMLConvert.toString (this. Sent); Writer.WriteEndelement (); // Title Writer.writeEndelement (); // Titler; Writer.WriteStartElement ("body"); writer.writeeendDocument (); Writer.WriteEndDocument () ; // Close all open tag} This code generates the following XML document <email> <headers> <header> <name> recipient </ name> <value> Michealb@example.org </ value> </ Header> <header> <name> sender </ name> <value> Dareo@example.com </ value> </ header> <header> <name> topic </ name> <value> Hello World </ value > </ Header> <header> <name> Send time </ name> <value> 2004-03-05T15: 54: 13.5446771-08: 00 </ value> </ header> </ headers></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-51613.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="51613" 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.039</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 = '_2Bm_2BVsbPf5k8EP8mfpU8BCYmLKu5cOCy_2FSuapl8qRveCUbnuxHu4zG3ZGo3SsmOMm70LKSh5JAUkZ3nmxCSC7FQ_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>