locked
CREATE JS OBJECT BASED ON XML RRS feed

  • Question

  • Hi,

    I am trying to adapt a piece of code I found on the internet as part of a tutorial to transform an xml into a javascript object but am struggling to get it to read attributes as well.

    Currently, it only reads node values but I would like it to read attribute values as well and add the attribute values to the object.

    That is how I call the function below. I pass an empty object and an xml node

    var ret = new Object();

    var xmlElem = 'This is an xml document that looks like this:'

    <AnchorDate>
        <Month value="2">Month</Month>
        <Year value="2007">Year</Year>
    </AnchorDate>

    res =  setPropertiesRecursive(ret, xmlElem)

    Then I can use the object like this:

    res[i].Month
    res[i].Year

    But I need to have access to the attribute values as well like this:

    res[i].Month.value
    res[i].Year.value


    I would appreciate very much if someone could help me to find a solution.

    Cheers

    C
    function setPropertiesRecursive(obj, node) 
    {
        if (node.childNodes.length > 0) 
        {
            for (var i = 0; i < node.childNodes.length; i++) 
            {
                if (node.childNodes[i].nodeType == 1 &&
                      node.childNodes[i].firstChild) 
                {
                    // If node has only one child
                    // set the obj property to the value of the node
                    if (node.childNodes[i].childNodes.length == 1) 
                    {
                        obj[node.childNodes[i].tagName] =
                            node.childNodes[i].firstChild.nodeValue;
                    }
                    // Otherwise this obj property is an array
                    // Recurse to set its multiple properties
                    else 
                    {
                        obj[node.childNodes[i].tagName] = [];
                        // Call recursively -- rinse and repeat
                        // ==============
                        setPropertiesRecursive(
                            obj[node.childNodes[i].tagName],
                            node.childNodes[i]);
                    }
                }
            }
        }
    }
    Thursday, September 17, 2009 10:53 AM