nitsuj
nitsuj

Reputation: 780

jQuery: get all children from XML

I would like to get all children from XML document and put the name into a variable = value. The script needs to be dynamic - the xml node name will be passed to the script, nothing hard coded. For example, if the user of the xml file wants to add an node, he can pass that variable to the JavaScript, and it will reference that node in the XML file.

$.ajax({
            type: 'GET',
            url: xmlDoc,
            dataType: 'xml',
            success: function(xml) {
                $(xml).find('Event').each(function() {

                }

What to put inside of the .find('Event') function? $(this).children() returns an object containing each node name under <Event></Event> (e.g. EventLocation), and $(this).children().text() returns the each value (e.g. Office Building 1).

I would like to add a variable for each node of the xml file, equaling it's value.

Example XML file would be:

<Events>
    <Event>
        <EventLocation>Office Building 1</EventLocation>
    </Event>
</Events>

Upvotes: 0

Views: 659

Answers (1)

Koen Peters
Koen Peters

Reputation: 12916

So, you want to create a new variable who's name is the tag name and its value is the value of that tag.

I don't think this can be done except by using the eval function, which I do not think is a good idea for a number of reasons. But because you asked it... here you go:

$(xml).find('Event').children().each(function() {
  eval(this.nodeName.toLowerCase() + '="' + $(this).text() + '"');
});

This will create the variables for you. It is however very dirty and error prone. If the tag name contains characters that cannot be used as variable names it will crash. Also eval is slow and can be misused by hackers. Depending on what you want to do you have other options like using an associative array

Upvotes: 1

Related Questions