Most developers who start using the PHP's DOM extension sometimes get confused by the concept of
DOMNodeList. In the DOM terminology, a node list is an ordered collection of nodes which has a length and an item property. The former returns the number of elements contained within the node list, while the latter accepts an integer as its value (starting from 0) by which you can access a given node within that list. The DOM specifications (created by the W3C) state that a node list is actually an interface, not an array. PHP implements this component as a class (object), not as an array (thus following the DOM specifications).
Showing posts with label xml. Show all posts
jQuery and XML: tutorials and resources
jQuery and XML are a powerful combination. In this post I'll provide a series of useful links to tutorials and resources already present on the web so that you can get an idea of how far you can go with jQuery and XML.
jQuery: XML and CDATA sections
One of the main abilities of jQuery is its advanced XML parsing during an AJAX request. All of this preprocessing lies under the hood, but becomes more evident when it comes to XML CDATA sections. In XML, CDATA sections are particular sections of the document enclosed between
<![CDATA[ and ]]>, which basically tell the XML parser to handle their contents as character data, that is, to not parse such contents as markup. For example, in an RSS or Atom feed you can find something like this:
Introduction to XML
XML is a universal format for data exchange on the web. In its essence, XML is a markup language like HTML, but with a stricter syntax. In this post I'll outline the main features of XML and its differences with HTML.
XML: IDs and the DOM
In XML, IDs are treated differently from HTML. Since XML has no predefined DTD, an ID attribute has no special meaning for a user-agent that tries to access an element through the DOM. Further, since browsers (the most used UAs on the web) don't use DTDs when they access documents, even if you specify and ID attribute in your custom DTD (by using
ATTLIST) the default browser's behavior won't change. The only way you have to mimic the basic functionalities of HTML DOM is to add the XHTML namespace to your target element or to its nearest ancestor.
XML: Frequently Asked Questions (FAQ)
In this post I'll try to answer to the most frequently asked questions (FAQ) about XML. I think there's currently a lot of confusion among web developers regarding this standard. There's actually an urgent need for an explanation that aims to be as clear and concise as possible.
CSS: styling an XML table
XML can contain a wide variety of data, including tabular data. Since XML has no predefined DTD which can tell a browser how such data must be presented, it's up to CSS to present it as a normal HTML table. In this post I'm going to show you how to write a CSS file for making an XML structure appear as an HTML table. First of all, we need an XML structure to work with, like the following:
XML DTD tutorial
DTDs are a basic building block of any valid XML document. In fact, DTDs provide a simple reference grammar to validate our XML documents. A DTD tells to a validating XML parser what kind of content, attributes or elements can actually be contained within another element. In this post I'm going to discuss with you some basic aspects of the DTDs, explaining why they are so useful.
XML and JSON: a comparison
XML is a descriptive markup language. What's more, XML is able to provide detailed descriptions of complex data structures. Many developers think that JSON is enough for them, but they're wrong. JSON is useful when you have to describe simple data structures, because JSON is not extensible. For such reason, JSON turns out to be perfect when the resource you're describing doesn't change much over time. But for dynamic structure, the extensibility of XML plays a major role. For example, JSON is excellent for a resource such as an RSS feed. This kind of resource has a predefined set of elements and attributes which is always the same on the entire web. On the contrary, JSON is inadequate when it comes to describe a complex framework or application.
Working with HTML elements in XML
Usually XML and HTML meet rarely, but there are some cases when HTML elements must be contained within an XML document. This won't be a problem, since both languages derive from SGML and thus are mutually compatible. Instead, problems arise when you want to display such HTML elements with their default display role and with their attributes, such as
style. Since XML treats these elements by default as anonymous elements, one solution would be using XSLT to transform HTML elements. But there's also another solution. Consider for example the case of RSS and Atom feeds. We have all noticed that these formats allow for the use of HTML elements inside their element, for example description or entry. How this can be done without XSLT?
This is possible thanks to the default XHTML namespace (http://www.w3.org/1999/xhtml) that can be specified on an element or more elements. When a browser encounters this namespace, it automatically binds the element(s) to the XHTML DTD. Browsers don't have a validating parser, so they don't read the DTD attached to a DOCTYPE declaration, but they're able to use namespaces to assign roles to elements. For example, if you have something like this:
<description xmlns="http://www.w3.org/1999/xhtml"> <h2>Title</h2> <p>Some text.</p> </description>
then the elements within description will be displayed with the default role assigned to normal h2 and p elements because they're both contained inside the XHTML namespace. This works because XHTML is basically XML, including the way browsers handle namespaces.
Adding JavaScript to XML
Adding JavaScript to XML is a little bit tricky. I first used to transform the target XML document into an HTML one by using XSLT. It worked fine, but I was frustrated by the idea of adding another PI to the XML set. So I asked myself: how can a browser recognize a
script element as such? In fact, if you try to add this kind of tag to an XML document, the script and everything is contained within the tag is parsed as CDATA so that nothing happens except viewing the contents of your script displayed on the page.
The answer is simple: a browser recognizes a script because it is part of an HTML DTD. More precisely, in the case of XML the DTD in question is an XHTML DTD. But this is not enough: a browser recognizes a script element not only because is part of the XHTML DTD, but also because it lives within the XHTML global namespace, which is also an XML standard namespace. The global XHTML namespace is as follows:
http://www.w3.org/1999/xhtml
This namespace must be added to the root element of your XML document. By doing so, browsers will treat your scripts as normal XHTML elements, because they live inside the XHTML namespace. Example:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.w3.org/1999/xhtml">
<para>Test</para>
<script type="text/javascript">
<![CDATA[
alert(document.getElementsByTagName('para')[0].firstChild.nodeValue); // alerts 'Test'
]]>
</script>
</root>
As you can see, the root element has the default XHTML namespace attached to it. In this way, the script element is parsed as an XHTML element and not as a generic XML element.
Web development without Internet Explorer
As a matter of fact, for years Internet Explorer has slowed down the global development of web standards and, more broadly, the entire future of the web. For years web developers have been forced to, as Ian Hickson says, code to the lowest common denominator instead of coding to the standards. As a result, now many developers still use a small percentage of the full potential of web standards not because they don't know how to code properly, but because they're afraid of what consequences might result in Internet Explorer.
For example, all JavaScript frameworks devote a significant amount of their inner routines to mitigate the differences between Internet Explorer and the other browsers. Further, the power of CSS3 features is still underused because of the support in Internet Explorer which is still far from getting the level of Firefox, Safari, Chrome, and Opera. What's more, XML and XSLT still rely on the presence of the MSXML library to exploit all their potentialities to the full. Finally, the most advanced features of the latest DOM specifications are still a theoretical thing in Internet Explorer.
How much time we devote to rethink a full website in terms of compatibility with IE? Sure, we're talking about backward compatibility here, the same thing that should make the web look like the old, good '90s, with GIF animations, dial-up modems and no AJAX, no CSS, all tables and, if we are lucky, JavaScript popups. Do you really think your web development process in terms of backward compatibility? I think the majority of developers would all agree to view the web from the forward compatibility point of view. Do you really like the idea of writing a CSS file made up only of class and ID selectors? I guess not.
Do you really enjoy the practice of duplicating your code when you want to use XPath on Internet Explorer? Do you still like all the quirks, bugs, inconsistencies that come along with IE's implementation of web standards? That's quite masochistic, in my opinion. Instead, rethink the web in terms of new features that may be added now, today or in the future. Embrace the future, not the old, sinking relics of a bigon age when the e-mail was the only practical implementation of web communication.
In a nutshell: test in Internet Explorer, if this makes you feel relieved but code just as if IE doesn't exist.
Linking CSS and XML documents
It's a well known fact that CSS can be used to stylize XML documents. The simplest way to link CSS and XML together is using a particular processing instruction like this:
<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="test.css" type="text/css"?>
This PI (processing instruction) works exactly as the link element in HTML. So if we have a simple XML document like this:
<document xmlns:doc="http://www.namespaces/document/doc">
<doc:title>A Test</doc:title>
<doc:body>
<doc:heading level="1">Title</doc:heading>
<doc:para>Text</doc:para>
</doc:body>
</document>
we can give it the following simple styles:
@namespace doc 'http://www.namespaces/document/doc';
document {
display: block;
width: 100%;
height: 100%;
min-height: 100%;
background: silver;
}
doc|title {
display: block;
background: gray;
color: #fff;
padding: 1em;
font-weight: bold;
text-align: center;
}
doc|body {
display: block;
padding: 2em 0;
width: 50%;
margin: 0 auto;
}
doc|heading[level="1"] {
display: block;
font-size: 2em;
font-weight: bold;
margin-bottom: 1em;
}
doc|para {
display: block;
font-style: italic;
}
and get the result depicted in the following picture.
Using JSON and XML
This video is a very detailed introduction to the use of JSON and XML with the Facebook API using PHP as development language. It's very useful if you want to have an overall idea about how the entire structure of the Facebook API works with JSON and XML.
jQuery: selecting XML namespaces
jQuery was originally built with a syntax which quite resembled the XPath's formal grammar. This was due to the fact that jQuery can actually support both HTML and XML. But what happens when an XML document contains namespaces? Here's an example:
<book xmlns:xdc="http://www.xml.com/books">
<xdc:bookreview>
<xdc:title>XML: A Primer</xdc:title>
<xdc:author>Simon St. Laurent</xdc:author>
<xdc:price>31.98</xdc:price>
<xdc:pages>352</xdc:pages>
<xdc:date>1998/01</xdc:date>
</xdc:bookreview>
</book>
In this case we have six elements which live inside the main namespace of the book element. Further, all these element have an XML suffix so that it's impossible to select them using normal jQuery's selectors. A good solution to this problem is using the namespaceURI and localName DOM properties to parse the above fragment. Here's how:
$(document).ready(function(){
var NS = 'http://www.xml.com/books';
var contents = [];
$('book').find('*').each(function() {
if($(this).get(0).namespaceURI == NS) {
var local = $(this).get(0).localName;
var content = $(this).text();
var domBit = local + ': ' + content;
contents.push(domBit);
}
});
$('<ul></ul>').appendTo('body');
for(var i= 0; len = contents.length, i<len; i++) {
var part = contents[i];
$('<li></li>').text(part).appendTo('ul');
}
});
As you can see, we test the namespace stored in the NS variable against the namespace contained in each element. Further, the localName property is used to access the local name of each element, that is, the string that comes after the ':' token in an XML full qualified name. Notice that I had to use the CSS universal selector to access the children elements of book because any other approach would return null or rise a JavaScript error.
Unfortunately, IE6 and 7 don't support the aforementioned DOM properties. However, if we insist on supporting obsolete browsers, we'll probably miss one important thing: the web is evolving and there's no time for dinosaurs.
CSS: default styles for XML elements
When dealing with CSS and XML is crucial to understand how XML is rendered by default in a web browser. Since XML has no default DTD associated with it, it's practically impossible for a web browser to give default styles to XML elements. In fact, XML elements have no default styles. Unlike HTML and XHTML elements, XML elements are all rendered as inline elements. It's up to the web developer to stylize XML elements. However, there are a couple of things you need to know before doing this.
The root element
The root element is not "magic" as in HTML. Its width and height and, consequently, its background color will not automatically stretch to cover the whole viewport. You have to manually set this behavior in your style sheet:
root {
display: block;
width: 100%;
height: 100%;
background: silver;
min-height: 100%;
}
Class and ID selectors
Class and ID selectors have a different meaning in XML. In fact, they're not considered as a part of the default set of attributes of an element. So the following rules will fail:
element.foo {color: blue;}
section#bar {color: green;}
Instead, you should use attribute selectors for this task, like so:
element[class="foo"] {color: blue;}
section[id="bar"] {color: green;}
Namespaces
For namespaces, you must use namespace selectors, like so:
@namespace element 'http://www.site.com/ns/elements/element';
element|ns {color: blue;}
Default display roles
Since all XML elements are displayed as inline by default, you must explicitly set a default display role for each element in your style sheet using the display property and its values. Example:
para {display: block;}
item {display: list-item;}
E4X - Primitive XML
Check out this SlideShare Presentation:
XML: avoiding namespace collision
XML namespaces were originally designed to avoid confusion between elements sharing the same characteristics. However, namespace should be created very carefully in order to avoid any possible collision. The first thing you need to bear in mind is that namespaces must have an higher degree of specificity than generic or public namespaces. For example, this is a perfectly valid XML namespace:
<document xmlns="http://www.site.com/ns/document" />
The problem with this namespace, however, is that is too generic, thus allowing for a possible collision. Instead, you should always choose a more specific namespace, for example by using the name of your website or web application, like so:
<document xmlns="http://onwebdev.blogspot.com/ns/elements/document" />
It's still true that other persons can actually use your namespaces on their websites, but it's also true that using a major level of specificity adds more semantics to your namespaces and, consequently, makes the risk of namespace collision less likely. Bear in mind that the purpose of namespaces is not trying to have absolutely unique IDs, but avoiding confusion between resources that may feature similar characteristics.
Using JSON as a blog RSS feed
JSON is gaining its momentum. Many websites have started using this format as their default format of choice for data exchange. One of the main reasons behind this choice is that JSON is a simple and lightweight format. RSS, on the other hand, is basically XML, implying that this format is more suitable when you have to deal with complex data structures, since XML is particularly useful for adding semantics to describe data (think about RDF, for example).
An RSS feed, in its basic structure, is actually simpler than most developers think. For example, take a look at the following excerpt taken from a sample RSS feed:
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Liftoff News</title>
<link>http://liftoff.msfc.nasa.gov/</link>
<description>Liftoff to Space Exploration.</description>
<language>en-us</language>
<pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
<lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<generator>Weblog Editor 2.0</generator>
<managingEditor>[email protected]</managingEditor>
<webMaster>[email protected]</webMaster>
<item>
<title>Star City</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
<description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's <a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm">Star City</a>.</description>
<pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
</item>
<!--more item elements here-->
</channel>
</rss>
As you can see, this is not a too complex structure. Using JSON, you can rewrite the above feed like so:
{"rss": {
"channel": {
"title": "Liftoff News",
"link": "http://liftoff.msfc.nasa.gov/",
"description": "Liftoff to Space Exploration",
"language": "en-us",
"pubdate": "Tue, 10 Jun 2003 04:00:00 GMT",
"lastbuilddate": "Tue, 10 Jun 2003 09:41:01 GMT",
"docs": "http://blogs.law.harvard.edu/tech/rss",
"generator": "Weblog Editor 2.0",
"managingEditor": "[email protected]",
"webmaster": "[email protected]",
"item": [
{
"title": "Star City",
"link": "http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp",
"description": "...",
"pubdate": "Tue, 03 Jun 2003 09:39:21 GMT",
"guid": "http://liftoff.msfc.nasa.gov/2003/06/03.html#item573"
}
// more items here
]
}
}
}
This is only a showcase to demonstrate that some peculiarities of the JSON format are really interesting from a development point of view. Most of all, a JSON feed is noticeably faster to parse than a normal XML/RSS feed and requires less resources. Further, all server-side languages include some methods or functions to encode and decode JSON data. Finally, it's worth to be mentioned that now the vast majority of web browsers are able to parse JSON natively.
XML and accessibility
A year ago I took a seminar in Milan where I spoke on the future possibilities of XML when applied to blogs (you can see the slides here). Many people got impressed when I showed them how to create a blog entirely written in XML, transformed with XSLT and displayed with CSS.
In the meantime, I had a nice conversation with Livio Mondini, who pointed out some interesting remarks on my conference. First of all, XML poses some accessibility problems when it comes to screen readers. In fact, since XML has no predefined DTD, screen readers don't know in advance how to handle XML elements. Simply put, a screen reader will ignore the element together with its content.
I didn't test extensively what happens when you transform an XML document with XSLT. This would be a useful test to do. Theoretically speaking, a screen reader should be able to recognize the transformed XML element but only when the target format is HTML (which, of course, has a predefined DTD). However, since screen readers read only what a browser reads (that is, the output provided by a web browser), what happens when a browser doesn't support XML and XSLT properly? That's another interesting question.
In other words, if the current browser is Internet Explorer 6, which by default doesn't read XML unless you activate the correct linking to the MSXML library, what a screen reader will read? I can't test it myself because I do not have a screen reader installed on my computer. I leave this test to you. If you find out something interesting, please let me know.
