I need to parse an XML flat file with JavaScript, and I'm struggling with how to use the DOM to select one particular node via an attribute then use its child nodes to populate some values. [more]
(Let's get one thing out of the way first: I don't think I can use XSLT. Please prove me wrong, but the problem is that I'm taking the XML node values and using them in a JavaScript function (that calls runs embedded Flash videos), and by rule don't I have to enclose JavaScript within an XSLT stylesheet inside CDATA, thus meaning any XSLT tag inside won't be parsed?)
(Oh, and my DBA is so overwhelmed there's no way I can get his attention to give me some tables before July... and I need this done a week ago.)
Anyway, here's the basic XML, really simplified:
<root>
<president ident="Clinton_Bill" />
<name> William J. Clinton </name>
<video url="http://someurl.com/clinton.flv" />
</root>
What I want is to have a query string on the URI, then use the value of that query string to match it against the ident attribute on president and if it matches use that node's values on the page.
In XSLT, I would set a param we'll call "query" and give it a value of the query string, then select root/president[@ident = $query].
So, how do I do this bit in JavaScript? I know how to load the node through XMLHTTPRequest and other methods, but how do I traverse the node until I find the right one? I'm thinking I run a for-next loop and if the attribute value matches process it, but that seems... inefficient. Is that the only way? Is there a better way?
I've gone through a dozen pages, but I haven't found anyone attempting to do this, which seems really strange to me. And, admittedly, JavaScript is my weakest web language, so there's that going against me.
Depending on the assumptions you can make about the structure of the XML, you can also be smarter. Like use document.getElementsByTagName (if you're not using XML namespacing) to find all the <president/>s.
Alternatively, the major web browsers support a subset of XPath via selectNodes() and selectSingleNode().
posted by Khalad at 5:11 PM on May 30, 2007