Skip to main content
October 10, 2006
Question

Help required with writing an xml parser function

  • October 10, 2006
  • 1 reply
  • 223 views
Hi guys

I'm trying to write a function that will parse through an xml document and store the contents into variables,
I can write it by using lots of for and if loops (which is a lot of code if there are lots of nodes) however i'm pretty sure there's a really neat and concise way of writing it in a function call that calls itself if there are childNodes, but I can't get my head around the logic,

Can anyone give me some suggestions as to how to write such a function?

Here is some example code which i'm using at the moment....


//check for child nodes for node 1
for (i=0; i<this.childNodes.length; i++) {
_root["node"+i+"Name"] = this.childNodes .nodeName;
_root["node"+i+"Value"] = this.childNodes
.nodeValue;
//check for child nodes for node 2
if (this.childNodes .hasChildNodes()) {
for (j=0; j<this.childNodes
.childNodes.length; j++) {
_root["node"+i+"."+j+"Name"] = this.childNodes .childNodes.nodeName;
_root["node"+i+"."+j+"Value"] = this.childNodes
.childNodes.nodeValue;
//check for child nodes for node 3
if (this.childNodes .childNodes.hasChildNodes()) {
for (k=0; k<this.childNodes
.childNodes.childNodes.length; k++) {
_root["node"+i+"."+j+"."+k+"Name"] = this.childNodes .childNodes.childNodes.nodeName;
_root["node"+i+"."+j+"."+k+"Value"] = this.childNodes
.childNodes.childNodes.nodeValue;
}
}
}
}
}

Is it possible to convert this code into a concise function that will call itself if there are any childNodes?

Many thanks for your responses :-)
This topic has been closed for replies.

1 reply

Participating Frequently
October 10, 2006
You should look into the XPath API, I find it to be way more useful for this sort of thing. It basically allows you to address nodes using wildcards and isn't heavily dependent on parenting, etc.

Try:
http://www.macromedia.com/go/xpathapi