Last time I gave you a short introduction into XML. I covered the very beginning of what it is, what you use it for, and I even showed you an example file. This time, I’d like to show you how to work with your XML in a web browser, Then I’d like to show you a quick parser using JavaScript.
Ready to go?
Awesome!
If you open this file in another tab/window, you can see it rendered in your web browser. As you can see the whole file is displayed. If you’re in Internet Explorer or FireFox (or most other browsers), you should see a + in front of any element that has child elements. In our case, the document element has a +, but no other elements.
These allow you to collapse or expand elements that you want to consider. This becomes very helpful when you want to look for a certain piece of data in the XML file. I’d like to point out that all your browser is doing is showing you your file without performing any action on it. No UI has been applied to your document. If you would like to apply some UI to it, you can include
<?xml-stylesheet type="text/css" href="demoLayoutFile.css"?>
Just after your xml header, and define how the XML should be displayed. Each element name you use would then be available to define CSS to control. I’m not going to get into CSS here, since that’s outside the scope of XML. If you want me to build a CSS series, let me know!
Applying UI is about all you can do with a browser…at least until you start programming. And I’m going to introduce you to that now with a little JavaScript. If you want to learn more, let me know. I’ll build posts about JavaScript and XML then.
<HTML> <HEAD> <TITLE>Retrieving data from an XML document</TITLE> <XML ID="firstXML" SRC="demo.xml"></XML> <SCRIPT LANGUAGE="JavaScript"> function getData() { xmldoc= document.all("firstXML").XMLDocument; nodeDoc = xmldoc.documentElement; nodeHeading = nodeDoc.firstChild; outputMessage = "Heading: " + nodeHeading.firstChild.nodeValue; message.innerHTML=outputMessage; } </SCRIPT> </HEAD> <BODY> <CENTER> <H1>Retrieve data from an XML document</H1> <DIV ID="message"></DIV> <P> <INPUT TYPE="BUTTON" VALUE="Read the heading" ONCLICK="getData()"> </CENTER> </BODY> </HTML>
If you save this off to your machine, along with the demo.xml file from before, you can see that JavaScript can parse your XML file quite easily!
You can dig into far more detail with Javascript, but before writing your own parser, look into any one of the many other parsers out there. I personally like PrototypeJS, It’s also a great start for learning AJAX!
If you have any questions, send them in. I’m here to help!