Saturday, August 25, 2012

XML Don't


Here are some technologies you should try to avoid when using XML.

Internet Explorer - XML Data Islands

What is it? An XML data island is XML data embedded into an HTML page.

Why avoid it? XML Data Islands only works with Internet Explorer browsers.

What to use instead? You should use JavaScript and XML DOM to parse and display XML in HTML.

For more information about JavaScript and XML DOM, visit our XML DOM tutorial.

XML Data Island Example

This example uses the XML document "cd_catalog.xml".

Bind the XML document to an <xml> tag in the HTML document. The id attribute defines an id for the data island, and the src attribute points to the XML file:

Example

This example only works in IE
<html>
<body>

<xml id="cdcat" src="cd_catalog.xml"></xml>

<table border="1" datasrc="#cdcat">
<tr>
<td><span datafld="ARTIST"></span></td>
<td><span datafld="TITLE"></span></td>
</tr>
</table>

</body>
</html>

Try it yourself »

The datasrc attribute of the <table> tag binds the HTML table to the XML data island.

The <span> tags allow the datafld attribute to refer to the XML element to be displayed. In this case, "ARTIST" and "TITLE". As the XML is read, additional rows are created for each <CD> element.

Internet Explorer - Behaviors

What is it? Internet Explorer 5 introduced behaviors. Behaviors are a way to add behaviors to XML (or HTML) elements with the use of CSS styles.

Why avoid it? The behavior attribute is only supported by Internet Explorer.

What to use instead? Use JavaScript and XML DOM (or HTML DOM) instead.

Example 1 - Mouseover Highlight

The following HTML file has a <style> element that defines a behavior for the <h1> element:
<html>
<head>
<style type="text/css">
h1 { behavior: url(behave.htc) }
</style>
</head>
<body>

<h1>Mouse over me!!!</h1>

</body>
</html>
The XML document "behave.htc" is shown below (The file contains a JavaScript and event handlers for the elements):
<attach for="element" event="onmouseover" handler="hig_lite" />
<attach for="element" event="onmouseout" handler="low_lite" />

<script type="text/javascript">
function hig_lite()
{
element.style.color='red';
}

function low_lite()
{
element.style.color='blue';
}
</script>

Try it yourself »

Example 2 - Typewriter Simulation

The following HTML file has a <style> element that defines a behavior for elements with an id of "typing":
<html>
<head>
<style type="text/css">
#typing
{
behavior:url(typing.htc);
font-family:'courier new';
}
</style>
</head>
<body>

<span id="typing" speed="100">IE5 introduced DHTML behaviors.
Behaviors are a way to add DHTML functionality to HTML elements
with the ease of CSS.<br /><br />How do behaviors work?<br />
By using XML we can link behaviors to any element in a web page
and manipulate that element.</p>v </span>

</body>
</html>
The XML document "typing.htc" is shown below:
<attach for="window" event="onload" handler="beginTyping" />
<method name="type" />

<script type="text/javascript">
var i,text1,text2,textLength,t;

function beginTyping()
{
i=0;
text1=element.innerText;
textLength=text1.length;
element.innerText="";
text2="";
t=window.setInterval(element.id+".type()",speed);
}

function type()
{
text2=text2+text1.substring(i,i+1);
element.innerText=text2;
i=i+1;
if (i==textLength)
  {
  clearInterval(t);
  }
}
</script>

Try it yourself »

Friday, August 24, 2012

XML DOM Advanced


The XML DOM - Advanced

In an earlier chapter of this tutorial we introduced the XML DOM, and we used the getElementsByTagName() method to retrieve data from an XML document.
In this chapter we will explain some other important XML DOM methods.
You can learn more about the XML DOM in our XML DOM tutorial.

Get the Value of an Element

The XML file used in the examples below: books.xml.
The following example retrieves the text value of the first <title> element:

Example

txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Try it yourself »


Get the Value of an Attribute

The following example retrieves the text value of the "lang" attribute of the first <title> element:

Example

txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

Try it yourself »


Change the Value of an Element

The following example changes the text value of the first <title> element:

Example

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

Try it yourself »


Create a New Attribute

The XML DOM setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute.

The following example adds a new attribute (edition="first") to each <book> element:

Example

x=xmlDoc.getElementsByTagName("book");

for(i=0;i<x.length;i++)
  {
  x[i].setAttribute("edition","first");
  }

Try it yourself »


Create an Element

The XML DOM createElement() method creates a new element node.
The XML DOM createTextNode() method creates a new text node.
The XML DOM appendChild() method adds a child node to a node (after the last child).

To create a new element with text content, it is necessary to both create a new element node and a new text node, and then append it to an existing node.

The following example creates a new element (<edition>), with the following text: First, and adds it to the first <book> element:

Example

newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);

x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);

Try it yourself »

Example explained:
  • Create an <edition> element
  • Create a text node with the following text: First
  • Append the text node to the new <edition> element
  • Append the <edition> element to the first <book> element

Remove an Element

The following example removes the first node in the first <book> element:

Example

x=xmlDoc.getElementsByTagName("book")[0];
x.removeChild(x.childNodes[0]);

Try it yourself »

Note: The result of the example above may be different depending on what browser you use. Firefox treats new lines as empty text nodes, Internet Explorer does not. You can read more about this and how to avoid it in our XML DOM tutorial.

XML on the Server


XML files are plain text files just like HTML files.
XML can easily be stored and generated by a standard web server.

Storing XML Files on the Server

XML files can be stored on an Internet server exactly the same way as HTML files.
Start Windows Notepad and write the following lines:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <from>Jani</from>
  <to>Tove</to>
  <message>Remember me this weekend</message>
</note>

Save the file on your web server with a proper name like "note.xml".

Generating XML with ASP

XML can be generated on a server without any installed XML software.
To generate an XML response from the server - simply write the following code and save it as an ASP file on the web server:

<%
response.ContentType="text/xml"
response.Write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.Write("<note>")
response.Write("<from>Jani</from>")
response.Write("<to>Tove</to>")
response.Write("<message>Remember me this weekend</message>")
response.Write("</note>")
%>

Note that the content type of the response must be set to "text/xml".

If you want to study ASP, you will find our ASP tutorial on our homepage.

Generating XML with PHP

To generate an XML response from the server using PHP, use following code:

<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
echo "<note>";
echo "<from>Jani</from>";
echo "<to>Tove</to>";
echo "<message>Remember me this weekend</message>";
echo "</note>";
?>

Note that the content type of the response header must be set to "text/xml".

If you want to study PHP, you will find our PHP tutorial on our homepage.

Generating XML From a Database

XML can be generated from a database without any installed XML software.
To generate an XML database response from the server, simply write the following code and save it as an ASP file on the web server:

<%
response.ContentType = "text/xml"
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0;"
conn.open server.mappath("/db/database.mdb")

sql="select fname,lname from tblGuestBook"
set rs=Conn.Execute(sql)

response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<guestbook>")
while (not rs.EOF)
response.write("<guest>")
response.write("<fname>" & rs("fname") & "</fname>")
response.write("<lname>" & rs("lname") & "</lname>")
response.write("</guest>")
rs.MoveNext()
wend

rs.close()
conn.close()
response.write("</guestbook>")
%>

The example above uses ASP with ADO.

If you want to study ASP and ADO, you will find the tutorials on our homepage.

Transforming XML with XSLT on the Server

This ASP transforms an XML file to XHTML on the server:

<%
'Load XML
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("simple.xml"))

'Load XSL
set xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath("simple.xsl"))

'Transform file
Response.Write(xml.transformNode(xsl))
%>

Example explained
  • The first block of code creates an instance of the Microsoft XML parser (XMLDOM), and loads the XML file into memory.
  • The second block of code creates another instance of the parser and loads the XSL file into memory.
  • The last line of code transforms the XML document using the XSL document, and sends the result as XHTML to your browser. Nice!

Saving XML To a File Using ASP

This ASP example creates a simple XML document and saves it on the server:

<%
text="<note>"
text=text & "<to>Tove</to>"
text=text & "<from>Jani</from>"
text=text & "<heading>Reminder</heading>"
text=text & "<body>Don't forget me this weekend!</body>"
text=text & "</note>"

set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async=false
xmlDoc.loadXML(text)

xmlDoc.Save("test.xml")
%>

XML Encoding


XML documents can contain non ASCII characters, like Norwegian æ ø å , or French ê è é.
To avoid errors, specify the XML encoding, or save XML files as Unicode.

XML Encoding Errors

If you load an XML document, you can get two different errors indicating encoding problems:

An invalid character was found in text content.

You get this error if your XML contains non ASCII characters, and the file was saved as single-byte ANSI (or ASCII) with no encoding specified.


Switch from current encoding to specified encoding not supported.

You get this error if your XML file was saved as double-byte Unicode (or UTF-16) with a single-byte encoding (Windows-1252, ISO-8859-1, UTF-8) specified.

You also get this error if your XML file was saved with single-byte ANSI (or ASCII), with double-byte encoding (UTF-16) specified.


Windows Notepad

Windows Notepad save files as single-byte ANSI (ASCII) by default.
If you select "Save as...", you can specify double-byte Unicode (UTF-16).

Save the XML file below as Unicode (note that the document does not contain any encoding attribute):

<?xml version="1.0"?>
<note>
<from>Jani</from>
<to>Tove</to>
<message>Norwegian: æøå. French: êèé</message>
</note>

The file above, note_encode_none_u.xml will NOT generate an error. But if you specify a single-byte encoding it will.

The following encoding (open it), will give an error message:

<?xml version="1.0" encoding="windows-1252"?>

The following encoding (open it), will give an error message:

<?xml version="1.0" encoding="ISO-8859-1"?>

The following encoding (open it), will give an error message:

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

The following encoding (open it), will NOT give an error:

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


Conclusion

  • Always use the encoding attribute
  • Use an editor that supports encoding
  • Make sure you know what encoding the editor uses
  • Use the same encoding in your encoding attribute