XML is a very important base on which Web Services work, and, in conjunction with a number of client- and server-side languages, can be put to good effect.
Let's see how we can use XML and client side JavaScript to display the contents of a XML file, access child elements, manipulate elements, and more!
Browser Issues
When it comes to client side languages, browser incompatibilities are a major issue. But here, using XML and JavaScript, it's XML that's the issue: not all browsers support the parsing of XML documents.
I'll use IE6 to explain the codes. Browsers that don't support XML can't read these, so when you view an XML file in such a browser, it will simply ignore all the tags.
Sample XML File
Let's consider a sample XML file, which shows employee data and Turnover of a company:
<?xml version="1.0" ?>
<company>
<employee id="001" sex="M" age="19">Premshree Pillai</employee>
<employee id="002" sex="M" age="24">Kumar Singh</employee>
<employee id="003" sex="M" age="21">Ranjit Kapoor</employee>
<turnover>
<year id="2000">100,000</year>
<year id="2001">140,000</year>
<year id="2002">200,000</year>
</turnover>
</company>
Manipulating the XML file data using JavaScript
Load The XML File
You can load a XML fie from JavaScript like this:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile)
{
xmlDoc.async="false";
xmlDoc.onreadystatechange=verify;
xmlDoc.load(xmlFile);
xmlObj=xmlDoc.documentElement;
}
Actually, just the last two lines of the function are enough to load the XML file. The previous two lines ensure that any JavaScript functions that we may use to manipulate the XML file data later, will not perform any function on an uninitialized object. Thus the function verify()is called:
function verify()
{
// 0 Object is not initialized
// 1 Loading object is loading data
// 2 Loaded object has loaded data
// 3 Data from object can be worked with
// 4 Object completely initialized
if (xmlDoc.readyState != 4)
{
return false;
}
}
Now the XML file can be loaded:
loadXML('xml_file.xml');
Display The Contents of the XML File
View the entire contents of the XML file using alert(xmlObj.xml); The whole XML file will be displayed in an alert box as it is, with proper indentation.
Children and Nodes
In the above XML file, <company> is the top level tag under which all other tags fall. These tags are called children. This XML file can be represented graphically like a folder-tree:

In the above XML file, the top level tag <company> has 4 children.
The numbering of children (as is usual in all languages) starts from 0 (zero). The <turnover> tag has 3 children under it.
We can find the number of children a tag has by using the childNodes.length property. Thus the number of children of <company> tag (here, 4) can be found by using xmlObj.childNodes.length
The number of children of <turnover> tag (here, 3) can be found by using xmlObj.childNodes(3).childNodes.length
Here we use childNodes(3) because <turnover> is the 3rd child of <company>
Test for Children
You can test whether a particular node child has any children using childNodes(i).hasChildNodes
Thus, xmlObj.childNodes(3).hasChildNodes() will return true. xmlObj.childNodes(2).hasChildNodes() will return false, as the <employee> tag doesn't have any children.
Get Tag Name
You can get the tag name of a child using childNodes(i).tagName. Thus, xmlObj.tagName will return "company". xmlObj.childNodes(0).tagName will return "employee". xmlObj.childNodes(3).childNodes(0).tagName will return "year".
Display the Content of a Tag
In the XML file, the content of the 1st <employee> tag is "Premshree Pillai". You can get this value using xmlObj.childNodes(0).firstChild.text
xmlObj.childNodes(2).firstChild.text will return "Suhasini Pandita". Similarly, xmlObj.childNodes(3).childNodes(1).firstChild.text will return "140,000".
Attributes
In the XML file, the <employee> tag has 3 attributes. An attribute can be accessed using childNodes(i).getAttribute("AttributeName"). Thus, xmlObj.childNodes(0).getAttribute("id") will return "001". xmlObj.childNodes(1).getAttribute("age") will return "24". And xmlObj.childNodes(2).getAttribute("sex") will return "F".
There are many more properties and methods available, and, using these, you can create many client side applications. The main advantage of using XML with JavaScript is that editing data becomes very easy. As XML is structured, it makes the management of content very easy. One example is a folder-tree menu. Another one is a JavaScript Ticker. You can find the full code an an example of this XML-based JavaScript Ticker at DynamicDrive.
We will create a XML based JavaScript Ticker that can display any number of messages. The ticker reads its contents (i.e. the ticker style), the text to be displayed, and the link for that particular message from an XML file. We'll call the XML file ticker_items.xml.
The structure of the XML document is as follows:
<?xml version="1.0"?>
<ticker>
<tickerstyle
pause = "true" / "false" "true" for pause onMouseOver
timeout = positive integer The delay in seconds b/w messages
border = positive integer The border width of Ticker
bordercolor = #HexColor The border color of Ticker
background = #HexColor The background color of Ticker
width = positive integer Ticker width
height = positive integer Ticker height
/>
<tickerlinkstyle>
<mouseout
font = "verdana,arial,helvetica..." Ticker link font
color = #HexColor Ticker link color
decoration = "none" / "underline" /
"underline + overline" Ticker link style
weight = "normal" / "bold" Ticker link weight
size = <positive integer>pt Ticker link size
/>
<mouseover
font = "verdana,arial,hevetica..." Ticker link font
color = #HexColor Ticker link color
decoration = "none" / "underline" /
"underline + overline" Ticker link style
weight = "normal" / "bold" Ticker link weight
size = <positive integer>pt Ticker link size
/>
</tickerlinkstyle>
<tickeritem
URL = A valid URL Ticker link URL
target = "_blank" / "_top" / "_self" /
<any other valid target name> Ticker link target
> Ticker item 1 text </tickeritem>
<tickeritem ...> Ticker item 2 text </tickeritem>
...
</ticker>
XML Ticker Script
<script language="JavaScript1.2">
// XML Ticker JavaScript
// (c) 2002 Premshree Pillai
// http://www.qiksearch.com
// Use freely as long as all messages are as it is
// Location of script:
http://www.qiksearch.com/javascripts/xml/ticker.htm
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile)
{
xmlDoc.async="false";
xmlDoc.onreadystatechange=verify;
xmlDoc.load(xmlFile);
ticker=xmlDoc.documentElement;
}
function verify()
{
if (xmlDoc.readyState != 4)
{
return false;
}
}
loadXML('ticker_items.xml');
document.write('<style type="text//css">');
document.write('.ticker_style{font-family:' +
ticker.childNodes(1).childNodes(0).getAttribute('font') + ';
font-size:' +
ticker.childNodes(1).childNodes(0).getAttribute('size')
+ '; color:' +
ticker.childNodes(1).childNodes(0).getAttribute('color') +
'; font-weight:' +
ticker.childNodes(1).childNodes(0).getAttribute('weight') +
'; text-decoration:' +
ticker.childNodes(1).childNodes(0).getAttribute('decoration')
+ '}');document.write('.ticker_style:hover{font-family:' +
ticker.childNodes(1).childNodes(1).getAttribute('font') +
'; font-size:' +
ticker.childNodes(1).childNodes(1).getAttribute('size')
+ '; color:' +
ticker.childNodes(1).childNodes(1).getAttribute('color') +
'; font-weight:' +
ticker.childNodes(1).childNodes(1).getAttribute('weight') +
'; text-decoration:' +
ticker.childNodes(1).childNodes(1).getAttribute
('decoration') + '}<br>');
document.write('</style>');
document.write('<table style="border:' +
ticker.childNodes(0).getAttribute('border')
+ ' solid ' + ticker.childNodes(0).getAttribute('bordercolor') +
'; background:' + ticker.childNodes(0).getAttribute('background') +
'; width:' + ticker.childNodes(0).getAttribute('width') + '; height:'
+ ticker.childNodes(0).getAttribute('height') + '">
<tr><td><div id="ticker_space"></div>
</td></tr></table>');
var item_count=2;
var timeOutVal=(ticker.childNodes(0).getAttribute('timeout'))*1000;
var original_timeOutVal=timeOutVal;
var isPauseContent;
if(ticker.childNodes(0).getAttribute('pause')=="true")
{
isPauseContent=' onmouseover="setDelay();" onmouseout="reset();"';
}
else
{
isPauseContent='';
}
function setTicker()
{
document.all.ticker_space.innerHTML='<center><a href="' _fcksavedurl=""'" +
ticker.childNodes(item_count).getAttribute('URL') + '" target="'
+ ticker.childNodes(item_count).getAttribute('target') +
'" class="ticker_style"' + isPauseContent + '>' +
ticker.childNodes(item_count).firstChild.text + '</a></center>';
if(item_count==ticker.childNodes.length-1)
{
item_count=2;
}
else
{
item_count++;
}
setTimeout("setTicker()",timeOutVal);
}
function setDelay()
{
timeOutVal=10000000000000;
item_count--;
}
function reset()
{
timeOutVal=original_timeOutVal;
setTicker();
}
setTicker();
</script>
As you can see in the source code, the ticker reads:
- all the messages to be displayed,
- the links for each message,
- the target for each URL,
- the ticker static style,
- the roll-over style,
- border width, color and background,
- the delay between messages, and more, from the XML file.
So if you want to change any parameter of the Ticker, all you have to do is make necessary changes in the XML file.
The ticker shown here is a basic ticker that rotates messages at an interval that is specified in the XML file. There are many effects you could add to the ticker like 'Fading message' or 'Teletypewriter'. You could also add features to change the ticker speed, or to list all messages in an instant!
本文介绍如何利用XML与JavaScript实现客户端应用开发,包括加载XML文件、显示内容、操作元素等技巧,并通过实例展示如何创建可自定义样式的XML驱动的滚动消息组件。
4942

被折叠的 条评论
为什么被折叠?



