Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to parse an XML document but i am a little bit confused just how i go about it. For example below shows my XML document

<document>
    <object name="Customer" type="class" x="137" y="63">
        <attributes>
        </attributes>
        <methods>
        </methods>
    </object>
    <object name="Item" type="class" x="539" y="275">
        <attributes>
        </attributes>
        <methods>
        </methods>
    </object>
    <link start="Customer" end="Item" type="generalization" />
</document>

In my case i need to loop through each "object" and create an object, in my app, this is simple enough: objectArray.push(new uml_Class(name));.

Now how would i loop through each <object> on the document and then insert its name value into an array?

I've read that the function getElementsByTagName()is to be used but this does not work for me:

alert(documentXML);
var root = documentXML.getElementsByTagName('Object');

It does alert my XML in the documentXML variable but then firebug tells me the following: documentXML.getElementsByTagName is not a function

How would i loop through an XML document, repeatedly making objects?

share|improve this question
have you ever tried documentXML.all["object"]? – Mark Linus May 9 '12 at 0:12

2 Answers

You may be interested in jQuery's built in XML parsing capabilities.

Example (borrowed from link):

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "books.xml",
        dataType: "xml",
        success: xmlParser
    });
});

function xmlParser(xml) {

    $('#load').fadeOut();

    $(xml).find("Book").each(function () {

        $(".main").append('<div class="book"><div class="title">' + $(this).find("Title").text() + '</div><div class="description">' + $(this).find("Description").text() + '</div><div class="date">Published ' + $(this).find("Date").text() + '</div></div>');
        $(".book").fadeIn(1000);

    });

}
share|improve this answer

As it is a XML document, tag names are not case invariant.

var objects = documentXML.getElementsByTagName('object');

should work. document.getElementsByTagName() is available on all Document object, I fear you missed to parse the string with a DOMParser.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.