XML DOM in IE

Source: Internet
Author: User
Tags add format error code net string string format version variable
Dom|xml When Microsoft first joined the XML support in IE 5.0, they were simply implementing XML functionality in the MSXML ActiveX library (originally designed to resolve active channels components in IE 4.0). The original version was not intended for public use, but as the developer became aware of the component and tried to use it, Microsoft realized the importance of the library and soon released the MSXML fully upgraded version in IE 4.01. MSXML was originally a component of IE. Until 2001, Microsoft released MSXML 3.0, a product that was released independently of its company's website. Later in 2001, Microsoft released MSXML 4.0 and renamed it the Microsoft XML Core service component. MSXML evolved from a basic, checksum-free XML parser to a powerful component that validates XML documents, transforms XSL, supports namespaces, simple XML APIs (SAX), and the common-document XPath and XML Schema standards, And each new version has a certain improvement in performance. To create an ActiveX object in JavaScript, Microsoft implements a new ActiveXObject class, which is used to instantiate ActiveX objects. The constructor for the ActiveXObject class contains a string parameter that represents the version of the ActiveX object to be created, which refers to the version of the XML document. The first XML DOM ActiveX object is named Microsoft.XMLDOM, and its creation method is as follows: var oxmldom = new ActiveXObject ("Microsoft.XMLDOM"); this newly created XML Dom objects, like other DOM objects, can be used to traverse the DOM tree and manipulate DOM nodes. By the deadline of this book, there are five different versions of the MSXML DOM document: Q microsoft.xmldom;q  MSXML2. domdocument;q  MSXML2. domdocument.3.0;q  MSXML2. domdocument.4.0;q  MSXML2. domdocument.5.0. MSXML is an ActiveX based implementation and can only be used on Windows platforms. IE 5 on the Mac platform is not supported by the XML DOM. Because there are five different versions and you always use the latest version, it is useful to use a function to determine which version the browser is using. This ensures the best possible performance with the latest XML support. BelowThe function createdocument () will enable you to create the correct MSXML DOM document. function createdocument () {    var aversions = ["MSXML2. domdocument.5.0 ",      " MSXML2. domdocument.4.0 "," MSXML2. domdocument.3.0 ",      " MSXML2. DOMDocument "," Microsoft.XMLDOM "   ];      for (var i = 0; i < Aversions.length; i++) {         Try {              var oxmldom = new ActiveXObject (Aversions[i]);              return oxmldom;        } catch (Oerror) {               //Do not do any processing       }   }    throw new Error ("MSXML is not installed."); This function traverses the aversions array that holds the version number of the MSXML DOM document and attempts to create the DOM from the latest version msxml2.domdocument.5.0Document. If the object is successfully created, the object is returned and the CreateDocument () is exited, otherwise the Try...catch statement catches the thrown exception and continues the next loop to try the next version. If the MSXML DOM document creation fails, an exception is thrown stating that MSXML is not installed. Because the function is not a class, the usage will return a value similar to other functions: var oxmldom = createdocument (); using the CreateDocument () function will ensure that the program uses the most recent DOM document. When you create an XML document, the next step is to load the XML data. 1. Loading XML data MSXML in IE supports two methods of loading XML: Load () and Loadxml (). The load () method loads an XML file from a specified location on the web. As with XMLHTTP, the load () method loads data in either synchronous or asynchronous mode. By default, the load () method takes the asynchronous mode, and if you want to take synchronous mode, you must set the Async property of the MSXML object to False, as follows: Oxmldom.async = False, and when asynchronous mode is used, The MSXML object exposes the ReadyState property, which, like the ReadyState property of XMLHTTP, contains five states. In addition, the DOM document supports the onReadyStateChange event handler function, which can monitor the readystate properties. Because the asynchronous mode is the default option, setting the Async property to True is optional: Oxmldom.async = True;oxmldom.onreadystatechange = function () {    if (oxmldom.readystate = 4) {       //perform certain operations when document is fully loaded    }};o Xmldom.load ("Myxml.xml"); In this example, the fictitious, named Myxml.xml XML document is loaded into the XML DOM document. The code in the IF statement is executed when the readystate value is 4 o'clock, stating that the document is fully loaded. The second method of loading XML data is Loadxml (), which differs primarily from the load () method by loading XML from a string rather than loading it with the specified filename. The string must contain well-formed XML, as follows: var sXml = "<Root><person><name>jeremy mcpeak</name></person></root> "; OXmlDom.loadXML (SXML) In this case, the Oxmldom document loads the XML data contained in the SXML variable. The Loadxml () method does not need to check the ReadyState property like the Load () method, nor does it need to set the Async property, because the method does not involve a server request. 2. Traversing an XML DOM document in IE traversal of XML DOM documents is very similar to the traversal of the HTML DOM, as they are all hierarchical structures of nodes. The topmost part of the node tree is the DocumentElement property, which contains the root element of the document. Using the properties listed in Table 4-1, you can access any element or attribute in the document. Table 4-1 XML Dom Properties
Property Description
Attributes An array containing the properties of the current node
ChildNodes Contains an array of child nodes
FirstChild Point to the first child node of the current node
LastChild Point to the last child node of the current node
NextSibling Returns the next neighbor node of the current node
NodeName Returns the name of the current node
NodeType Specifies the XML DOM node type for the current node
NodeValue Text containing the current node
Ownerdocument Returns the root element of a document
ParentNode Point to the parent node of the current node
PreviousSibling Returns the previous neighbor node of the current node
Text Returns the contents of the current node or the text of the current node and its child nodes (properties that are supported only by IE)
Xml Returns the XML of the current node and its child nodes as a string (properties that are supported only by IE)
Traversing the DOM document and getting the data is a straightforward process. Let's look at the following XML document: <?xml version= "1.0" encoding= "Utf-8"?><books>    <book isbn= " 0471777781 ">professional ajax</book>    <book isbn=" 0764579088 ">Professional" JavaScript for Web developers</book>    <book isbn= "0764557599" >professional C#</book >    <book isbn= "1861002025" >professional Visual Basic 6 databases</book></books > This is a simple XML document that contains a root element <books/> and four child elements <book/>. Take this document as an example, we can study the DOM details. The DOM tree is constructed based on the relationships between nodes. A node may contain other nodes or child nodes. Another node may have the same parent node as the other nodes, which we call the neighbor node. If you want to get the first <book/> element in the document, simply access the FirstChild property to achieve the goal: var oroot = Oxmldom.documentelement;var Ofirstbook = Oroot.firstchild; assigning documentelement to Variable oroot can save program space and input content, although this is not required. You can use the FirstChild property to refer to the reference of the first child element <books/> of the root element <books/> and assign it to the variable Ofirstbook. The same purpose can be achieved by using the ChildNodes collection: var oFirstBook2 = oroot.childnodes[0]; Selecting the first item in the ChildNodes collection returns the first child node of the root node. Because ChildNodes is the nodelist type in JavaScript,Use the Length property to get the number of child nodes, as follows: var ichildren = oRoot.childNodes.length; In this example, because the document element has four child nodes, the Ichildren value is 4. As mentioned earlier, a node can have child nodes, which means that it can have a parent node. The ParentNode property allows you to select the parent node of the current node: var oparent = ofirstbook.parentnode; variable Ofirstbook is mentioned earlier in this section, but it is now the first in the document <book/ > element, so its parentnode attribute refers to the DOM's DocumentElement attribute, which is the <books/> element. If the current node is a book element, then how do you choose another book element? Because <book/> elements have a common parent node, they are neighbor to each other. The NextSibling and PreviousSibling properties allow you to select the adjacent node of the current node. The NextSibling property points to the next neighbor, and the previoussibling attribute points to the previous neighbor: var osecondbook = Ofirstbook.nextsibling;ofirstbook2 = Osecondbook.previoussibling This code references the second <book/> element and assigns it to Osecondbook. The value of the OFIRSTBOOK2 is unchanged by osecondbook the neighbor node to oFirstBook2 the variable. If the node does not have the next neighbor node, then nextsibling is null. The same is true for previoussibling, if the current node has no previous neighbor node, then previoussibling is also null. Now that we know how to traverse the document structure, the next thing we need to know is how to get the data from the tree's nodes. For example, you can use the Text property to get the literal containing the third <book/> element, as follows: the var stext = oroot.childnodes[2].text;text Attribute (Microsoft-specific attribute) can get all the text nodes that the node contains. This property is quite useful. If there is no Text property, the Access text node must be: var stext = oroot.childnodes[2].firstchild.nodevalue; This code gets the same result as the previous code using the Text property. Similar to the previousexample, use the ChildNodes collection to refer to the third <book/> element, and use FirstChild to point to the text node of the <book/> element because the text node is still a node in the DOM. You can get the text by using the NodeValue property to get the value of the current node. The results from these two examples are the same, but there is a major difference between using the Text property and using the NodeValue property of the literal node. The Text property gets the value of all text nodes that contain the current element and its child nodes, and the NodeValue property can only get the value of the current node. Although it is a useful property, it may return more content than expected. For example, suppose we modify an XML document to: <?xml version= "1.0" encoding= "Utf-8"?><books>    <book "isbn=" 0471777781 ">        <title>professional ajax</title>         <author>nicholas C. Zakas, Jeremy McPeak, Joe fawcett</author>     </book>    <book isbn= "0764579088" >professional JavaScript for WEB developers </book>    <book isbn= "0764557599" >professional c#</book>    < Book isbn= "1861002025" >professional Visual Basic 6 databases</book></books> The new XML document in the first <book/> Two new child node:<title/> element (title),<author/> Element (author) is added to the element. Once again we makeWith the Text property: Alert (Ofirstchild.text), there is no new content in the code, we can look at the results shown in Figure 4-1. Figure   4-1 Note that at this point we will get the text nodes of the <title/> and <author/> elements and connect them together. This is the difference between text and nodevalue. The NodeValue property can only get the value of the current node, and the Text property will get all the text nodes that contain the current node and its child nodes. MSXML also provides other methods for obtaining specific nodes or values, the most common method being getattribute () and getElementsByTagName (). The GetAttribute () method will accept a string parameter containing the property name and return the property value. If the specified property does not exist, the returned value is null. We will also use the XML document mentioned earlier in this section to see the following code: var sattribute = Ofirstchild.getattribute ("ISBN"); alert (sattribute); This code gets the first < Book/> the ISBN attribute value of the element, assigns it to the variable sattribute, and then displays the value using the alert () method. The getElementsByTagName () method returns the nodelist of a child element, based on the name specified by its parameter. The method searches only for elements in a given node, so the returned nodelist does not contain any external elements. For example: var cbooks = oroot.getelementsbytagname ("book"); alert (cbooks.length); This code gets all the <book/> elements in the document, and assigns the returned nodelist to the variable cbooks. For the previous XML document example, the warning box will display the four <book/> elements found. If you want to get all the child nodes, you must use "*" as the parameter to the getElementsByTagName () method, whose code looks like this: var celements = oroot.getelementsbytagname ("*"); Because the previous XML document example contains only <book/> elements, the result of this code is the same as the previous example. 3. Get XML data in IE to get XML data just use one attribute, that is, XML. This property serializes the XML data for the current node. Serialization (serialization) is the objectThe process of converting to a simple, storage, or transfer format. XML attributes convert XML to a string, including the complete label name, attributes, and text: var sXml = Oroot.xml;alert (sXml); This code serializes the XML data from the document element and passes it as an argument to the alert () method. The following is a partially serialized xml:<books><book isbn= "0471777781" >professional ajax</book></books> The serialized data can be loaded into another XML DOM object, sent to the server, or passed to another page. The serialized XML data returned through the XML property depends on the current node. If the XML attribute is used at the DocumentElement node, the XML data for the entire document is returned, and if it is used only on the <book/> element, the XML data contained by that <book/> element is returned. The XML property is a read-only property. If you want to add elements to your document, you must use the DOM method to implement them. 4. Operation Dom in IE now, we've learned how to traverse the DOM, extract information from the DOM, and convert XML into string format. The next thing to learn is how to add, remove, and replace nodes in the DOM. l   Create nodes use the DOM method to create many different nodes. The first is the element created with the createelement () method. Pass in a parameter to the method, indicate the element label name to create, and return a reference to xmldomelement: var Onewbook = oxmldom.createelement ("book"); o XmlDom.documentElement.appendChild (onewbook); This code creates a new <book/> element and adds it to the documentelement through the AppendChild () method. The AppendChild () method adds the new element specified by its parameter and takes it as the last child node. In this case, however, an empty <book/> element is added to the document, so you also need to add some text to the element: var Onewbook = oxmldom.createelement ("book"); var onewbooktext = Oxmldom.createtextnode ("Professional. NET 2.0 Generics"); Onewbook.appendchild (Onewbooktext); OXmlDom.documentElement.appendChild (onewbook); This code passes createTextNode () method creates a text node and adds it to the newly created <book/> element through the AppendChild () method. The createTextNode () method has only one string parameter to specify the value of the text node. You have now created a new <book/> element from the program, provided a text node for it, and added it to the document. For this new element, you also need to set the ISBN attribute for it, like other neighbor nodes. This is simple, as long as you can create a property by using the SetAttribute () method, which applies to all element nodes. var onewbook = oxmldom.createelement ("book"); var onewbooktext = Oxmldom.createtextnode ("Professional. NET 2.0 Generics" ); Onewbook.appendchild (Onewbooktext); Onewbook.setattribute ("ISBN", "0764559885"); o XmlDom.documentElement.appendChild (Onewbook); In the above code, the newly added row is used to create the ISBN property and assigns its value to 0764559885. The SetAttribute () method has two parameters: the first argument is the property name, and the second argument is the value assigned to the property. For adding attributes to an element, IE provides some other methods, but they are not actually better than setattribute () and require more coding. l   Delete, replace, and insert nodes if you can add nodes to the document, it also means that you can delete the nodes. The RemoveChild () method is used to implement this functionality. The method contains a parameter: the node to be deleted. For example, to remove the first <book/> element from a document, you can use the following code: var oremovedchild = Oroot.removechild (oroot.firstchild); RemoveChild () method returns the deleted child nodes, so the Oremovechild variable points to the deleted <book/> element. When you have a reference to the old node, you can place it in theanywhere in the document. If you want to replace the third <book/> element with the element that Oremovedchild points to, you can implement it through the ReplaceChild () method, which returns the replaced node: var oreplacedchild = Oroot.replacechild (Oremovedchild, oroot.childnodes[2]); the ReplaceChild () method accepts two parameters: the newly added node and the node that will be replaced. In this code, the third <book/> element will be replaced with the node referenced by the Oremovedchild variable, and the reference of the substituted node will exist in the Oreplacedchild variable. Because the Oreplacechild variable is a reference to a substituted node, it can be easily inserted into the document. You can use the AppendChild () method to add it to the end of a child node list, or you can use the InsertBefore () method to insert the node before a node: Oroot.insertbefore (Oreplacedchild, Oroot.lastchild); This code inserts the previously replaced node before the last <book/> element. The use of the LastChild property is very similar to the firstchild selection of the first child node, which allows you to get the last child node. The InsertBefore () method accepts two parameters: the node to be inserted and the node that represents the insertion point (before the insertion point is before that node). The method also returns the value of the inserted node, but is not required in the example above. As you can see, Dom is a fairly powerful interface that enables you to access, delete, and add data. 5. Handling errors in IE in the process of loading XML data, errors may be thrown for different reasons. For example, an external XML file cannot be found, or the XML format is incorrect. To handle these situations, MSXML provides a ParseError object that contains an error message. For each XML DOM document object created by MSXML, the object is one of the property values to which it belongs. We can check for errors by ParseError objects that are exposed to the ErrorCode property that is compared to integer 0. If ErrorCode is not equal to 0, an error occurs. The following example intentionally designs an error. var sXml = "<root><person><name>jeremy mcpeak</name></root>"; var oXmlDom = crEatedocument (); Oxmldom.loadxml (SXML); if (oXmlDom.parseError.errorCode!= 0) {    alert ("an Error occurred: "+ OXmlDom.parseError.reason);} else {   //When XML is loaded successfully you will notice that the,<person> element is incomplete in the highlighted line of code (no corresponding </person> tag). An error is generated because the XML to be loaded is not in the correct format. The errorcode is then compared to 0, and if not equal (not equal in this case), a warning is displayed that the error occurred. To implement this feature, you can use the reason property of the ParseError object to get the cause of the error. The ParseError object provides the following properties to help you better understand the error:q  errorcode: Error code (Long Integer);q  filepos: The location where the error occurred in the file (Long integer);q  line: The line number (Long integer) of the line that contains the error;q  Linepos: Where the error occurred in a particular row (long);q  reason: The cause of the error (String type);q  Srctext: The line of code where the error occurred (string type); q The URL (string type) of the   Url:xml document. Although these properties provide information about each error, which attribute should be used, it depends on your needs. ErrorCodeProperties can be positive or negative, only if ErrorCodeIt is 0 o'clock to indicate that no errors have occurred.


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.