JavaScript Advanced Programming Notes (18)

Source: Internet
Author: User
Tags tagname xml attribute xml dom document xml parser xpath xsl xslt


JavaScript and XML (a) browser support for XML DOM


The DOM2 level is the first specification that mentions the dynamic creation of XML DOM concepts. The DOM3 level further enhances the XML DOM.


1.dom2 level Core
Document.implementation.createDocument (NamespaceURI, Root, doctype);


When working with XML through JavaScript, you typically use only the parameter root, because this parameter specifies the label name of the XML DOM document element.


// Create a new XML document with document element <root>
         var xmldom = document.implementation.createDocument ("", "root", null);
        
         alert (xmldom.documentElement.tagName); // "root"
       
         var child = xmldom.createElement ("child");
         xmldom.documentElement.appendChild (child); 





Passing a null character to a namespace means that no namespace is specified, and passing NULL to the document type means that the document type is not specified. The variable xmldom holds an instance of the DOM2 level document type.



This example shows the label name of the document element and creates and adds a new child element to the document element.






In fact, a DOM file is often parsed into a DOM structure, or vice versa.





2.DOMParse type


Parsing XML into a DOM document



Before parsing the XML, create the Domparter instance before calling the Parseformstring () method. This method receives two parameters: the XML string to parse and the content type (text/xml), and the return value is an instance of document.





   var xmldom = document.implementation.createDocument("", "root", null);
        
        alert(xmldom.documentElement.tagName);  //"root"
       
        var child = xmldom.createElement("child");
        xmldom.documentElement.appendChild(child);





Only well-formed XML can be parsed and HTML cannot be parsed as an HTML document.



ie9+ Firefox Safari Chrome Opera


3.XMLSerializer type


Serializing a DOM document as an XML string



Create an instance of XmlSerializer first, and then pass the document to its serializetostring () method


 var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(xmldom);
        alert(xml);





ie9+ Firefox Safari Chrome Opera





4.IE8 and previous versions of XML


Use the ActiveXObject constructor and pass it a string that represents the version of the XML document, preferably with Msxml2.domdocument. 6.0.



To parse an XML string, you first create a DOM document and then call the Loadxml () method.


 var xmldom = createDocument();
        xmldom.loadXML("<root><child/></root>");
        
        alert(xmldom.documentElement.tagName);  //"root"
        alert(xmldom.documentElement.firstChild.tagName); //"child"
        
        var anotherChild = xmldom.createElement("child");
        xmldom.documentElement.appendChild(anotherChild);








① Serialization of XML



IE each DOM node has an XML attribute that holds the XML string representing the node



② loading an XML file



Async Property: Specifies how the document is loaded, true to indicate asynchronous, false for synchronization, and true by default.



After determining how the XML document is loaded, call the load () method, and receive a parameter that is the URL of the XML file to be loaded.


 var xmldom = createDocument();
        xmldom.async = true;
        xmldom.load("example.xml");


Asynchronously loading an XML file requires an event handler for the Onreadystatechage event of the XML DOM document, and the 4 status indicates that the XML file is fully loaded and parsed as a DOM document. Its state can be obtained through the ReadyState property of the XML file. The statement that specifies the event handler for the onReadyStateChange event must be placed before the statement that calls the load () method. In an event handler, you must use the name of the XML document variable, and the This object cannot be used.





5. Working with XML across browsers
function parseXml (xml) {
             var xmldom = null;
             // Detect DOMParser
             if (typeof DOMParser! = "undefined") {
                 xmldom = (new DOMParser ()). parseFromString (xml, "text / xml");
                 // Detect returned documents,
                 var errors = xmldom.getElementsByTagName ("parsererror");
                 if (errors.length) {
                     throw new Error ("XML parsing error:" + errors [0] .textContent);
                 }
             } else if (typeof ActiveXObject! = "undefined") {
                 // Create the appropriate version of the XML document
                 xmldom = createDocument ();
                 xmldom.loadXML (xml);
                 if (xmldom.parseError! = 0) {
                     throw new Error ("XML parsing error:" + xmldom.parseError.reason);
                 }
             } else {
                 throw new Error ("No XML parser available.");
             }
            
             return xmldom;
         }




(ii) browser support for XPath


is a means to find a node in a DOM document





1.DOM3 level XPath


Xpathevaluator, Xpathresult is the most important type, xpathevaluator is used to evaluate an XPath expression in a specific context.



Evaluate: Evaluates XPath on a given context, based on specific namespace information. Receives 5 parameters: an XPath expression, a context node, a namespace solver, the type of the returned result, and the Xpathresult object that holds the result (usually null). Xpathresult.ordered_node_iterator_type is the most commonly used result type, which means that a matching node collection is returned, with the order of the document always.



If you specify a snapshot result type, you must use the Snapshotitem () method and the Snapshotlength property.


 
 
var result = xmldom.evaluate("employee/name", xmldom.documentElement, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
            while (element) {
                message += serializer.serializeToString(element) + "\n";
                count++;
                element = result.iterateNext()
            }





① Single-node results



Specifies that Xpathresult.first_ordered_node_type returns the first matching node, which can be accessed through the Singlenodevalue property of the result






② Simple Type Results



With Xpathresult Boolean, numeric, and string types, you can get a simple non-node data type that returns a value by Booleanvalue, Numbervalue, and StringValue, respectively.



For a Boolean value type, returns true if at least one node matches an XPath expression.


            var NULL NULL );            alert (result.booleanvalue);





For numeric types, you must specify an XPath function that returns a numeric value at the position of the XPath expression parameter, such as COUNT () that calculates the number of all nodes that match the given pattern.


            var NULL NULL );            alert (result.numbervalue);





③ Default Type Results



The Xpathresult.any_type can be used to automatically determine the type of the returned result, and to determine what result type is returned to detect the Resulttype property of the result.






④ namespace Support



Creatensresolver () to create a Xpathnsresolver object that receives a parameter, the node in the document that contains the namespace definition. Passing the Nsresolver object to evaluate () ensures that it understands the Wrox prefix used by the XPath expression.





  var xmldom = (new DOMParser()).parseFromString("<?xml version=\"1.0\</wrox:books>", "text/xml");
            var nsresolver = xmldom.createNSResolver(xmldom.documentElement);
            var result = xmldom.evaluate("wrox:book/wrox:author", 
                                         xmldom.documentElement, nsresolver,
                                         XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);





Or define a function that takes the namespace prefix and returns the associated URI.





XPath in 2.IE


IE9 and previous versions using XPath must use an ActiveX-based implementation.



Method: Selectsingenode (): Receives an XPath pattern that returns the first matching node when a matching node is found.



Seclectnodes (): Returns the nodelist of all nodes that match.






IE support for namespaces



You must know the namespaces used and create the string "xmlns:prefix1= ' Uri1 ' xmlns:prefix2= ' uri2 ' xmlns:prefix3= ' Uri3 '" in the format



This string must be passed into SetProperty (), receive two parameters, and set the property name and property value.





3. Using XPath across browsers




(iii) browser support for XSLT


XSLT is an XML-related technique that uses XPath to convert a document from one form of representation to another.





XSLT in 1.IE


① Simple XSLT transformations



Add the XSLT and XML to a DOM document, and then use the Transformnode () method to receive a parameter: A document that contains an XSLT style sheet. The call to the Transformnode () method returns a string containing the returned information.






② Complex XSLT transformations



Use XSL templates and XSL processors. The first one is to load an XSLT stylesheet into a thread-safe XML document that can be used by using msxml2.freethreadeddomdocument. The converted node is then assigned to the input property, and transform () is called.





2.XSLTProcessor type


Load two DOM documents, based on XML and XSLT, then create a new Xsltprocessor object and use the Importstylesheet () method to specify an XSLT for it.



If you want to return the full DOM document Call Transformtodocument (), you can use the result as a completely different DOM document as long as the XML DOM is passed in. Call Transformtofragment () to get a document fragment object.






TRANSFORMTOFRAGMENTJ () receives two parameters, the XML DOM to be exchanged, and the document that should have the result fragment, to insert the fragment into the page, as long as the ducoment is the second parameter.



The processor creates a fragment owned by the Ducument object that can add the returned fragment to the existing <div> element of the page.


 var fragment = processor.transformToFragment(xmldom, document);
            var div = document.getElementById("divResult");
            
            div.appendChild(fragment);





① Using Parameters



Xsltprocessor supports the use of Setparameter () to set the parameters of an XSLT, which receives three parameters: the namespace URI. The internal name of the parameter and the value to set. This method must be called before transformtodocument or transformtofragment () is called.



The GetParameter () and RemoveParameter () methods are used to obtain and remove values for the current parameter, respectively.






② Resetting the processor



To invoke the Reset method, remove all parameters and style sheets from the processor.





3. Using XSLT across browsers


Cross-browser compatibility the best XSLT transformation technology can only return strings, in IE only on the context node call Transformnode (), other browsers to serialize the results of the transformtodocument () operation.



Using IE's transformnode () ensures that you do not have to use a thread-safe DOM document for conversion.



JavaScript Advanced Programming Notes (18)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.