PDA

View Full Version : xml parse to named array


moskovich
12-28-2002, 10:35 PM
Ok. I've been trying for a while not to get this right...hopefully someon can help me finish it off:

I have an xml file that looks like this:




<?xml version="1.0"?>
<content>
<section id="Gymnastics">
<title>Gymnastics Information</title>
<description>text for gymnastics</description>
</section>
<section id="Physics">
<title>Physics Information</title>
<description>text for phyics</description>
</section>
<section id="Design">
<title>Design Information</title>
<description>text for design</description>
</section>
<section id="News">
<title>News Information</title>
<description>text for news</description>
<section id="Sub News">
<title>Sub News Information</title>
<description>text for Sub News</description>
<section>
</section>
</content>

I'm using these two function to parse the xml (onLoad):


function format(xmlObj) {
var children = new Array();
var child;
var i = 0;
children = xmlObj.childNodes;
while (i<children.length) {
child = children[i];
createPath(child, v);
//check to see what type of node this is
//where 1 is an XML element and 3 is a text node
if (child.nodeType == 3) {
//store the content
siteXML[lastSection][lastObj] = child.nodeValue;
} else {
//recursively loop since node is an object
format(child);
}
i++;
}
}
function createPath(child, nodePass) {
if (child.attributes.id != undefined) {
siteXML[child.attributes.id] = new Array();
lastSection = child.attributes.id;
} else if (child.nodeType != 3) {
siteXML[lastSection][child.nodeName] = new Array();
lastObj = child.nodeName;
}
}


I'm using the attribute "id" to represent the name of the section. My goal is to create a named array with the same hierarchical stucture as the xml file. Right now everything is loaded into one named array. I can't figure out how to account for nested sections.

Any ideas? Thanks!