XML and JavaScript in the browser

Source: Internet
Author: User
Tags processing instruction xml parser

XML and JavaScript in the browser

Before working with XML, you need to get it in JavaScript. This section shows a few different ways to get the XML in JavaScript and handle it.

Node type of XML

Before we look at how to deal with XML, let's look at the different nodes and types in the XML. If it is HTML, it is not necessary to understand these nodes, but because of the extensibility and structural uncertainties of XML, it is important to understand these intrinsic node types.

Here are 12 different nodes in the XML (table taken from the W3school Chinese site):

Node type

Describe

Document

Represents the entire document (the root node of the DOM tree)

DocumentFragment

Represents a lightweight document object that holds some of the documents.

DocumentType

Provides an interface to the entity defined for the document.

ProcessingInstruction

Represents a processing instruction.

EntityReference

Represents an entity reference element.

Element

Represents element (Element) elements

Attr

Represents a property.

Text

Represents the text content in an element or attribute.

Cdatasection

Represents a CDATA section in a document (text is not parsed by the parser)

Comment

Represents a comment.

Entity

Represents an entity.

Notation

Represents a symbol declared in a DTD.

You can use JavaScript to get a node and check its type. The code in Listing 13 returns true if the incoming node type is comment, otherwise false is returned. The code here does not involve jquery, but it is used when exploring the node values of XML later.


Listing 13. JavaScript function for determining if the node element is a comment

<script type= "Text/javascript" >

function isnodecomment (node) {

return (NODE.NODETYPE===8);

}

</script>

Each node type is not specifically described here, but familiarity with these nodes is critical to working with it and its values.

Processing XML with JavaScript on the client

Most of the code used to process HTML in the previous example can handle XML directly, and it is important to note that XML cannot rely on the id attribute to handle a node, and that it needs to be done in a more popular way with the name of the node. In addition, the size of the node name is sensitive when XML processing is performed.

Let's say we want to deal with the XML as shown in listing 14 below.

Listing 14. A Simple XML file

<?xml version= "1.0" encoding= "UTF-8"?>

<item content_id= "1" date_published= "2010-05-25" >

<description></description>

<body></body>

<related_items>

<related_item content_id= "2" ></related_item>

<related_item content_id= "3" ></related_item>

</related_items>

</item>

Get XML in JavaScript

To work with the XML in Listing 14, the first thing to do is to get it in JavaScript. There are many ways to do this:

    1. transferring XML to a string type on the server side to JavaScript
    2. Binding XML to a textarea control on the server side
    3. Loading XML into the browser via Ajax

The detailed steps for each of these methods are as follows:

    1. transferring XML to a string type on the server side to JavaScript

With a server-side programming language, XML can be converted into a string into a JavaScript variable. This method is not the most elegant and not the most special, but it does help. But the advantage of this approach is that you can load an XML file from anywhere, even a local server (see Listing 15).

Listing 15. Writing XML into a JavaScript variable from PHP

<?php

$xmlPath = "/path/to/file.xml"; or Http://www.somedomain.com/path/to/file.xml

$xmlFile = file_get_contents ($xmlPath);

?>

<script type= "Text/javascript" >

var xmlstring = "<?= $xmlFile?>";

</script>

    1. Binding XML to a textarea control on the server side

Another slightly different approach is to load the XML into a <textarea> (this element can not be displayed). The XML string is then fetched from the previously mentioned innerHTML and placed in JavaScript.

You can put this PHP variable containing XML into an <textarea> tag with an ID of "XML", which can then be easily obtained by this ID:

<textarea id= "xml" ><?= $xmlFile?></textarea>

You can then easily take the XML out of this HTML element and put it into JavaScript (see listing 16).

Listing 16. Exposing XML to JavaScript from a TEXTAREA element

<script type= "Text/javascript" >

var xmlstring = document.getElementById ("xml"). InnerHTML;

</script>

Consider browser compatibility, using the method in Listing 17 to create the DOM from an XML string.

Listing 17. Cross-browser JavaScript function for converting the XML string into a DOM object

<script type= "Text/javascript" >

/**

* Converts passed XML string into a DOM element.

* @param xmlstr {String}

*/

function getxmldomfromstring (XMLSTR) {

if (window. ActiveXObject && window. GetObject) {

For Internet Explorer

var dom = new ActiveXObject (' Microsoft.XMLDOM ');

Dom.loadxml (XMLSTR);

return DOM;

}

if (window. Domparser) {//For other browsers

return new Domparser (). parsefromstring (Xmlstr, ' text/xml ');

}

throw new Error (' No XML parser available ');

}

var xmlstring = document.getElementById ("xmlstring"). InnerHTML;

var xmlData = getxmldomfromstring (xmlstring);

</script>

Here's a look at the inverse process, which is to return an XML string from the XML DOM (see listing 18).

Listing 18. Cross-browser JavaScript function for returning a string representation of an XML DOM object

<script type= "Text/javascript" >

/**

* Returns string representation of passed XML object

*/

function getxmlasstring (xmlDom) {

Return (typeof xmlserializer!== "undefined")?

(New window. XMLSerializer ()). Serializetostring (XmlDom):

Xmldom.xml;

}

</script>

    1. Loading XML into the browser via Ajax

The last way to get XML in JavaScript is through Ajax. See the section on jquery later.

Working with XML in JavaScript

Let's look at some of the standard JavaScript methods mentioned earlier if applied to XML. To get the ID of the Description field and related entry for the current entry, you can do so with the code in Listing 19.

Listing 19. XML processing using JavaScript

<script type= "Text/javascript" >

Get value of single node

var descriptionnode = xmldata.getelementsbytagname ("description") [0];

var description

= Descriptionnode.firstchild && descriptionNode.firstChild.nodeValue;

Get values of nodes from a set

var relateditems = xmldata.getelementsbytagname ("Related_item");

XmlData is an XML doc

var relateditemvals = [];

var tempitemval;

for (var i=0,total=relateditems.length; i<total; i++) {

Tempitemval = Relateditems[i].firstchild? Relateditems[i].firstchild.nodevalue: "";

Relateditemvals.push (Tempitemval);

}

Set and get attribute of a node

Description.setattribute ("Language", "en");

Description.getattribute ("language"); Returns "EN"

</script>

Look closely at the code above. getElementsByTagName () This method, which has been seen before, is important for dealing with XML burial depths, because it allows you to get an XML element of the given name. (It is necessary to reiterate that casing is sensitive when working with XML). Then check to see if Descriptionnode contains child nodes to safely return the value of description. If there are child nodes, then you can access the NodeValue to get the values. When you want to get the text value of a particular node, things get a little harder. Although some browsers support the use of the previously mentioned innerHTML attribute in XML, most of them are not supported. So you need to first check if it contains FirstChild (text node Textnode, note node Comment, child node), if any, to access nodevalue. In the above code, an empty string is returned if a child node is checked to not exist.

Finally, you see that the SetAttribute () and GetAttribute () methods are used exactly as in HTML.

Here you have seen how to use the original JavaScript code to work with HTML and XML nodes. By introducing jquery in the next section, you will see how powerful the library is, not only simplifying the process but also making it easier for you to manipulate the DOM.

XML and JavaScript in the browser

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.