Embed XML Data in Web Page and Access it Using JavaScript
By Stephen Bucaro
You can embed your XML data in your web page document and access it using JavaScript. This ability
was originally provided by Internet Explorer 5.0, but Microsoft removed support for XML data islands
in Internet Explorer 10. Now, HTML5 has a feature called a data block which allows you to
embed XML data in a script block in your web page document and access it using JavaScript.
Shown below is an example XML data block for a book list.
<script id="book-catalog" type="application/xml">
<catalog xmlns="http://example.mozilla.org/PurchaseOrderML">
<book>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>
<book>
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<price>36.95</price>
</book>
<book>
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<price>36.95</price>
</book>
<book>
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<price>49.95</price>
</book>
</catalog>
</script>
You can get a pointer to the data block using the JavaScript getElementById method as shown below.
var bookItem = document.getElementById("book-catalog").textContent;
The XML can then be parsed into a DOM tree using the DOMParser API as shown below.
var parser = new DOMParser();
doc = parser.parseFromString(bookItem, "application/xml");
You can then access an XML element using the JavaScript getElementsByTagNameNS method as shown below.
var author = books[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "author")[0].textContent;
document.getElementById("author").value = author;
In this example, in order to step though the XML data, I initialize some global variables in the documents
window.onload event, as shown below.
<script>
var doc;
var books;
var numRecords;
var recNum;
function initData()
{
// get the XML data
var bookItem = document.getElementById("book-catalog").textContent;
// parse into a DOM tree using the DOMParser API
var parser = new DOMParser();
doc = parser.parseFromString(bookItem, "application/xml");
books = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "book");
numRecords = books.length;
recNum = 0;
}
window.onload = initData;
</script>
Then you can step though the XML data using a fnction as shown below.
function moveNext()
{
if(recNum < numRecords - 1) recNum += 1;
var author = books[recNum].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "author")[0].textContent;
document.getElementById("author").value = author;
}
The data block, DOMParser API method works in Firefox, Opera, Chrome, Safari, and Internet Explorer 9 and later.
The entire code for this example is shown on the next page.
|