简体   繁体   中英

Using Javascript To Parse XML and Create Objects From The Retrieved Values

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?

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);

    });

}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM