XML and ASP programming (1)

zhaozj2021-02-17  51

When the XML data is combined into the ASP application, the first thing you need to do is to access the contents of the XML file. From a technical manner, in the ASP environment, there are three main methods for reading and managing XML text: create a MSXML object, and load the XML document into the DOM; use server-side incrude, ssi; just like access Like other text files, use FileSystemObject to access the XML document; the fourth method is to create a built-in data island on the client, and explain later. First, use the DOM to use DOM in the ASP code, you need to create an instance of a Microsoft XML analyzer, which is instantiated as any other COM component, and you should add a few line standard code on the start of the page. These codes create an analyzer instance, load an XML document to the DOM, and set the root element (ie, document elements) to the current node. 'Instatiate the XML ProcessorSet objXML = Server.CreateObject ( "Microsoft.XMLDOM")' Load the XML DocumentobjXML.load (Server.MapPath ( "mydata.xml") 'Set the Document ElementSet objRootElement = objXML.documentElement is loaded in the XML document Before, you need to perform the fourth step, that is, set the validateonParse property to TRUE, ensuring that the loaded document is a valid XML document. This avoids the troubles encountered later: 'Instatiate the xml processorset ObjXml = Server.createObject ( "Microsoft.XMLDOM") 'The processos should validate the documentobjXML.validateOnParse = True'Load the XML DocumentobjXML.load (Server.MapPath ( "mydata.xml")' Set the Document ElementSet objRootElement = objXML.documentElement Finally, there An optional step, it also appears before loading. It requires synchronous load file: objxml.async = false This is said to load and verify a considerable file requires some time. Another replacement is ignored this step, allowed Non-synchronous load, this is the default, once these initialization steps are completed, the XML document is loaded, and the preparation of the processed. All important functions of Dom are configurable. Of course, just like any COM object After use, keep in mind that it must be destroyed: set objxml = Nothing 2, the server-side embedding server embedding can be used to insert an XML document code into the ASP page.

Third, use an ASP code to process XML example <% DIM Sourcefile, Source, RootElement, Htmlcode SourceFile = Request.ServerVariables ("Appl_Physical_Path") & "XML / Contacts.xml" set source = Server.CreateObject ( "Microsoft.XMLDOM") source.async = false source.load sourceFile set rootElement = source.documentElement HTMLCode = HTMLCode & "" HTMLCode = HTMLCode & rootElement.childNodes (0) .Text htmlcode = htmlcode & "

" htmlcode = htmlcode & rootElement.childNodes (0) .text htmlcode = HTMLCode & "

" htmlcode = htmlcode & rootElement.childNodes (0) .text htmlcode = htmlcode & "

"response.write (htmlcode) set source = Nothing%> john 111-1111-111 smith 222-2222-222 Mike 333-3333-333 XSL formatted XML Data StyleContact.asp <% sourcefile = server.mappath ("contact.xml") stylefile = server.mappath ("contact.xsl") Set Source = Server.createObject ("Microsoft.xmLDom") Source.async = false source.load (SourceFile) SETSTYLE =

Server.createObject ("Microsoft.xmldom") style.async = false style.Load (STYLEFILE) response.write (Source.TransformNode (style)%> Contact.xml zhou.zf 1111111111 1111111111 > listen 2222222222 bubu 3333333333 contact.xsl

< / xsl: template> other examples: 1, WEB link <% Dim objXML, objRootElement, strLinkName, strLinkURL, strLinkTarget, sourceFile, isourceFile = Request.ServerVariables ( "APPL_PHYSICAL_PATH") & "xml / Links.xml "set objxml = server.createObject (" Microsoft.xmLDom ") objxml.validateonParse = trueobjxml.async = falseobjXML.load (sourceFile) set objRootElement = objXML.documentElementfor i = 0 to objRootElement.childNodes.length-1 strLinkName = objRootElement.childNodes.item (i) .text strLinkURL = objRootElement.childNodes.item (i) .getAttribute ( "url ") Strlinktarget = objroterlement.childNodes.Item (i) .GetaTribute (" target ") response.write ("


") NextSet Objxml = Nothing%> links.xml Front Page 0 Front Page 1 Front Page 2 front points 3 < / RelatedLinks> 2, XML file generated gen_xml.asp generate XML </ title> </ head> <body> <% 'create an empty root node for the document. set rootnode = server.createObject (" aspxml.aspxml " ) Rootnode.Encoding = "ISO-8859-1" rootnode.standalone = "yes" rootnode.tag = "table" for row = 1 to 10 set rownode = rootnode.newchild ("row", ") for col = 1 To 10 set colnode = rownode.newchild ("Column", "& row &") ") Next Next Rootnode.savexml (Server.MApp ATH ("Table.xml")) SET ROOTNODE = NOTHING%> </ body> </ html> 3, adding node additem.asp <% if Request.servervariables ("request_method") = "post" Then Call Writexmlelse Call showformend IF</p> <p>Sub showform%> <html> <body> please enter the persons contact details <form action = "additem.asp" method = "post"> name: <input type = "text" name = "name"> Email: <input TYPE = "text" name = "email"> <input type = "submit" name = "submit" value = "add"> </ form> </ body> </ html> <% End Subsub Writexml 'Find XML file Path Dim strfilename, strXmlfile strfilename = "contacts.xml" strXmlfile = server.mappath (strfilename)</p> <p>'Standard "Create XML Object" Code Set OXML = Server.createObject ("Microsoft.xmLDom") oxml.async = false</p> <p>'Check file exists bitFileExists = oXML.load (strXMLFile) If bitFileExists Then tmpChildnodes = oXML.documentElement.childnodes.length - 1 intCurrentRecord = tmpChildnodes 1 Else' create xml oXML.appendChild (oXML.createProcessingInstruction ( "xml", "version = "" 1.0 "" ")) OXML.Appendchild (Oxml.createElement (" Contacts ")) INTCURRENTRECORD = 0 End IF</p> <p>'Create Record Set Oxmlrec = Oxml.createElement ("Contact")</p> <p>'Create an id attribute set oatt = oxml.createAttribute ("id") oatt.text = intCurrentRecord OxmlRec.setttributenode oatttt</p> <p>'Set Remaining Fields</p> <p>'name oxmlrec.Appendchild (Oxml.createElement ("name")) oxmlrec.childNodes (0) .text = request.form ("name")</p> <p>'email address oxmlrec.appendchild (Oxml.createElement ("email")) oxmlrec.childNodes (1) .text = request.form ("email")</p> <p>'Date stamp oXMLRec.appendChild (oXML.createElement ( "created")) oXMLRec.childnodes (2) .text = now ()' write new record oXML.documentElement.appendChild (oXMLRec.cloneNode (True))</p> <p>'Save File Oxml.save strXmlfile</p> <p>'redirect to xml file response.redirect (strfilename)</p> <p>OXML = Nothingend Sub%> Contacts.xml <? XML Version = "1.0"?> <contact_info> <contact id = "1"> <name> bubu </ name> <email> zhou813@163.com </ email> <created> 2003/04/29 9:26:51 <Contact ID = "2"> <name> 22222 </ name> <email> 22222222 <email> <created> 2003- 5-12 18:15:41 </ created> </ contact> </ contact_info></p> <p>4, Message ") = request.form (" homepage) = request.form ("homepage) = request.form (" homepage) = request.form ("homepage) = request.form (" homepage) Email = request.form ("homepage) email = request.form email ") text = Server.URLEncode (request.form (" text ")) posttime = now () sourceFile =" list.xml "strSourceFile = Server.MapPath (sourceFile) Set objXML = Server.CreateObject (" Microsoft.XMLDOM " ) blnRet = objXML.load (strSourceFile) If blnRet Then Set objRootlist = objXML.documentElement if objRootlist.hasChildNodes then id = objRootlist.lastchild.firstchild.text 1 else id = 1 end if Else objXML.appendChild (objXML.createProcessingInstruction ( " XML, "Version =" 1.0 "")) set objrootlist = objxml.createElement ("newlist") objxml.appendchild (objrootlist) ID = 1 End if Brstr = CHR (13) & chr (10) & chr (9) XMLNode = Brstr & "<List>" & Brstr & _ "<ID>" & id & "</ ID>" & Brstr & _ "<username>" & username & "</ usrname>" & bromtr & _ "<fromwhere>" & fromwhere & "</ Fromwhere> & brstr & _ <posttime> "& posttime &" </ posttime> "& brstr & _" <homepage> "& homepage &" </ homepage> "& brstr & _ <email> "& brrstr & _ <text>" & text & "</ text>" & brrs "</ list>" & chr (13) set objxml2 = server.createObject ("Microsoft. Xmldom ") Objxml2.LoadXml (XMLNode) set rootnewnode =</p> <p>objXML2.documentElement objRootlist.appendChild (rootNewNode) objXML.save (strSourceFile) set objXML = nothing set objXML2 = nothing response.redirect (strSourceFile) end if%> <html> <head> <title> Untitled Document </ title> <meta http-equiv = "content-type" content = "text / html; charSet = GB2312"> <style type = "text / css"> <! - td {font-size: 9pt} -> </ stop> </ head> <body bgcolor = "# 0099cc" text = "# 000000"> <table width = "80%" border = "0" cellspacing = "1" cellpadding = "4" align = "center" bgcolor = " #Fffffff> <form action = "postnew.asp" method = "post" name = "form1"> <tr bgcolor = "# 000000> <td colspan =" 2 "> <font color =" # ffffff "> New book </ font> </ td> </ tr> <tr> <td width = "19%" align = "right"> name: </ td> <td width = "81% "> <Input type =" text "name =" username "> ** </ td> </ tr> <tr bgcolor =" # efefef "> <td width =" 19% "align =" right "> comFrom: </ td> <td width = "81%"> <input type = "text" name = "fromwhere" value = "china"> </ td> </ tr> <tr bgcolor = "# efefef"> <TD width = "19%" a Lign = "right"> Website: </ td> <td width = "81%"> <input type = "text" Name = "homepage"</p> <p>Value = "http: //"> </ td> </ tr> <tr bgcolor = "# Efefef"> <td width = "19%" align = "right"> email: </ td> <td width = "81%"> <input type = "text" name = "email"> </ td> </ tr> <tr> "# efefef"> <td width = "19%" align = "right" valign = "TOP"> context: </ td> <TD width = "81%"> <textarea name = "text" cols = "60" rows = "10"> </ textarea> </ td> </ TR> < Tr BGColor = "# Efefef"> <td width = "19%" align = "right"> </ td> <td width = "81%> <input type =" submit "name =" Submit "value =" Submit> <input type = "reset" name = "submit2" value = "reset"> </ td> </ tr> </ form> </ table> </ body> </ html></p> <p>Fourth, use the DOM to generate XML Summary XML Document Object Model XML DOM contains four main objects: XmLDomDocument, XmLDomnode, XmLDomnodeList, and XMLDomnameDNodeMap. As with any other object model, each XML DOM object has its own characteristics and methods. This article, we will mainly introduce XmldomDocument and XMLDomnode objects. The XMLDOMDocument object XMLDOMDocument object represents the top layer node in the XML DOM level (please do not confuse the root point in the XML document). It is the basis for establishing and manipulating the XML structure. In order to create an XMLDOMDocument object variable, use the following createObject command: set objXmldoc = CreateObject ("Microsoft.xmLDom" table A: List the features and methods we can get after you have created an XMLDOMDocument object. The method described CreateAttribute create a new property CreateCDATASection create junction CreateComment DATA section to create a note CreateElement junction with the specified name to create an element node CreateEntityReference create an entity reference object CreateNode create junction CreateTextNode create a text node Load load an existing XML document Save to save XML Document Features Description PreserveWhitespace Indicates whether to display space T resolveexternals in an XML document parsing name, DTD, and external entity index ValidateonParse indicate whether the parser is legally checking DocumentElement Returns the root node setting of the XML document. Setting Run As you are in Table A As seen in, only the XMLDOMDocument object is created, you can create a single XML node. Before doing this work, you can also set up the XML document parsing the runtime, if you intend to generate an XML document directly to the browser, it is useful. Run option allows you to set asynchronous downloads, provide document legality checking and retention spaces, and parsing external indexes. In order to prevent asynchronous downloads, the Asynch characteristic is set to FALSE. If you plan to use a line of new characters instead of space, you can set the preserveWhitespace feature to True. Resolveexternals feature prevents parsing engines from parsing external entity indexes, document type definitions, or external domains.</p> <p>1. Creating a Node XMLDOMDocument object provides two ways to create nodes or XmLDomnode: CreateElement and Createnode. Select which method you need to provide the amount of information you need. When you use the CreateElement method, just provide node name, such as set objxmlroot = Objxmldoc.createElement ("Order_Status" When using the CreateNode method, you want to specify the node type, node name, and related names. (XML name domain allows you to create multiple XML elements with the same name in one document), for example, if you want to use the CreateNode method, you can write the following code: set objxmlroot = Objxmldoc.createnode ("Element", "Order_status", "Space1") Once you have created a node, you must add it into the XML document. This will use the appendchild method, for example, continue the above example, you can write: objxmldoc.Appendchild (Objxmlroot) This statement creates an XML root node. In addition to the appendchild method, the XMLDomnode object also has three other methods of three control XML nodes: ReplaceChild, RemoveChild and Insertbefore</p> <p>2. Once the attribute assignment of nodes, once the node is created, it is also assigned to its property, such as a separate identifier, or characteristic value. You have to use the SetAttribute method. This method receives two parameters - attribute names and attribute values. For example, the following code creates a property name Shipping_DataSource and attribute value north_atlantic_shippening: objxmlroot.settribute "shipping_datasource", "north_atlantic_shipping" At this point, we generated an XML document, and the SetAttributes method created a node property. 3. Join the sub-node To create a sub-node, you can use the CreateElement or CreateNode method we described earlier and add them to the appropriate parent node. For example, suppose, we have to create an XML node called Publisher_Disclaimer. To do this, we put the root node attached to the document, the code is as follows: Set objXMLChildTestNode = objXMLdoc.createNode ( "element", "PUBLISHER_DISCLAIMER", "") objXMLdoc.DocumentElement.appendChild (objXMLChildTestNode) Note : We use XMLDOMDocument's DocumentElement feature to add new knots to the root point of the XML document, to add sub-nodes, you just add them to the parent node. 4. Once all the nodes are created, you will need to assign them. That is the most important step of XML. To do this, you create a node as usual, then assign a TEXT attribute of the node. For example, the following code creates an XML node called published_date then assigned as follows: Set objPublishDate = objXMLdoc.CreateNode ( "element", "PUBLISHED_DATE", "") dShippedDate = FormatDateTime (Date, 2) objPublishDate.Text = dShippedDate objXMLChildTestNode .appendchild (ObjPublishDate) We assigned the current date to the Text property, then add this node to the Publisher_DiscLaimer element. 5. Using XML DOM under ASP To generate an XML document in the previous example, we can use ASP to generate. We will create a simple ASP page, let you only click the button to create an XML document. To accomplish this, we use an ASP page with a Windows script component, which is generated by XML. We will use Windows Script Component Wizard to generate initial code. (If you don't have Wizard, you can find it in Microsoft's script column.) (1) Creating a script component to run Windows Script Component Wizard. In the first window, enter XMLDOM as the component name, and then click Next. Confirm that VBScript and support Active Server Pages options are selected in the second window, and then click Next.</p> <p>In the fourth window, enter CREATEXML, as the only way for our script objects. Click Next twice, then click Finish. After completing these things, Wizard creates components and adds components to your desktop. At this point, we get the basic structure of the component, but it does not contain any features, so add functions. To do this, double-click the XMLDOM shortcut to the desktop. After completing, Windows shows the initial code in Notepad. Note that the component itself is an XML document. To add a CREATEXML code, we will create a sub-process instead of the function. So, remove the following row function createxml () createXML = "Temporary value" End function At the code (2) Constructs the ASP page to create an ASP web page, open the HTML editor you are familiar with, enter a list B The code in. Make sure the Window.NaviGate line points to the appropriate folder. To understand how it works, open this page in Internet Explorer. Once opened, there will be a message, telling you that XML has created success and an Show button appears, click the button. More content in the XML DOM library is as seen in the sample code, XML DOM contains more methods and properties than we described here. To find a complete XML document object model, please visit the Microsoft website. At the same time, how do you want to know about XML DOM and an example of advanced usage of XSL and ASP, please visit www.i3solutions.com/onlineDemos.asp. Conclusion 1, XML is developing rapidly, and the XML data model structure provides more functions than the text-centric web page, and the XML document object model can create an XML document for you by programming. In this article, we have introduced XML DOM and demonstrate how to use XML DOM in Active Server Pages.</p> <p>2, steps to write XML files: (1), object generate set obj = server.createObject ("Microsoft.xmLDom") (2), load XML file obj.load (SourceFileXML) (3), the knot in the original XML file Point to get set objrootlist = obj.documentelement (4), object generate set objnew = server.createObject ("Microsoft.xmLDom") (5), load new node Objnew.LoadXML (STRNEWNODE) ​​(6), new knot gets RootnewNode = Objnew.documentelement (7), load the new knots obtained by step (6) to the back Objrootlist.Appendchild (rootnewnode) (8) (8), saved xml file obj.save (8). SourcefileXML) (9), release the generated object set obj = Nothing set objnew = nothing</p> <p>5. XML Sensitive to case in XML, all elements must have an end tag, such as: <p> this is a paragraph </ p> <p> this is another paragraph </ p> pay attention : From the previous example you may have noticed, the XML declaration does not end the mark. This is not an error. Because the declaration is not part of the XML document. It is not an XML element, so it can't have end tags. XML is sensitive to case, this is not like HTML. In XML, tag <letter> and tag <letter> are different. Therefore, the case where the open and end tags should be written into the same: <Message> this is incorrect </ message> <message> this is correct </ message> all XML elements must be reasonable nested if the tag is unreasonable It is meaningless in XML. In HTML, some elements can be nested in unampler, for example: <b> <i> this text is bold and itract </ b> </ i> in XML, all elements must be rationally nesting each other For example: <b> <i> this text is bold and italic </ i> </ b> All XML documents must have a root mark in an XML document is the root mark. All XML documents must contain a tag pair to define root elements. All other elements must nest in the root element. All elements can have sub-elements. Both child elements must be nested in the mother element. <Root> <child> <subchild> ..... </ subchild> </ child> </ root> must cause the attribute value in XML, omitting the quotation marks around the attribute value is illegal. Like HTML, the name / value pair of XML elements can have attributes. In XML, the attribute value must be caused. Take a look at the two XML documents below.</p> <p>The first is correct, the second is wrong: <? XML Version = "1.0"?> <Note Date = 12/11/99> <to> TOVE </ to> <from> jani </ from> <Heading> Reminder </ Heading> <body> don't forget me this weekend! </ body> </ Note> <? XML Version = "1.0"?> <Note Date = "12/11/99> < To> TOVE </ to> <from> jani </ from> <heading> reminder </ heading> <body> don't forget me this weekend! </ body> </ note> Document The first error is The data attributes in the Note element are not caused. This is correct: DATE = "12/11/99". This is wrong: DATE = 12/11/99. In XML, space is reserved in XML, and the space for documents cannot be deleted. This is not like HTML. In HTML, such a sentence: Hello My Name is Tove will be displayed as this: Hello My Name is Tove, because HTML removes the space. In XML, CR / LF is converted to LF in XML, and a new line is usually stored as LF. Do you know what is a typewriter? The typewriter is a typewriter device used in the last century. When you play a line on the typewriter, you have to use it manually to the left on the left, then manually feed. In a Windows application, new lines in text are typically stored as CR LF character pairs. In UNIX applications, new lines are typically stored as an LF character. Some applications use only one CR character to store new rows. Reference: [1] "ASP and XML Advanced Programming"</p> <p>---------------- Author: Zhou Zhifeng (Dalian) Date: May 14, 2003 Email: zhou.zf@neusoft.com ---------- --------</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-30462.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="30462" 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.035</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 = 'UZwtbjSYnslXvOpv6nhoMbHoDjFhQFjgQhdafzPyBYU6xUdVYZQEqObIR967z_2BW96gR3QbBcsqLFAQaQ3rNufg_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>