Yarin Miran
Yarin Miran

Reputation: 3381

XML string manipulation in JS?

I have an XML file in a string in this format:

<item>
    <name>xxx</name>
    <id>yyy</id>

    <view>
        <name>view1_name</name>
        <view_attrs>
            <view_attr>
                <name>Age</name>
                <values>
                    <value>18-36</value>
                    <value>55-70</value>
                </values>
            </view_attr>
            <view_attr>
                <name>Status</name>
                <values>
                    <value>Single</value>
                    <value>Married</value>
                </values>
            </view_attr>
        </view_attrs>
    </view>


    <view>
        <name>view2_name</name>
        <view_attrs>
            <view_attr>
                <name>Age</name>
                <values>
                    <value>37-54</value>
                </values>
            </view_attr>
        </view_attrs>
    </view>


    <children>
        <item>
        ...
        </item>
        <item>
        ...
            <children>
            ...
            </children>
        </item>
    </children>

</item>

What I would like to do for example, is add/delete an item, a child, change values in a specific view_attr and so on?

What's the easiest and simplest method to do so?

Thanks in advance. :)

Upvotes: 7

Views: 4686

Answers (3)

Rakesh Pai
Rakesh Pai

Reputation: 26277

If cross-browser compatibility is not an issue, I'd strongly suggest looking at E4X. http://en.wikipedia.org/wiki/ECMAScript_for_XML It makes working with XML a pleasure. Currently only works in Rhino and Gecko.

Upvotes: 1

Josef Pfleger
Josef Pfleger

Reputation: 74527

jQuery wraps browser specific XML parsers so you can simply use the following to aquire a document from a string:

var xmlDoc = $('<foo><bar1/><bar2/></foo>')[0];

Now you can use standard DOM manipulation to add or delete nodes:

var bar2 = xmlDoc.getElementsByTagName('bar2')[0];
var bar3 = document.createElement('bar3');
xmlDoc.appendChild(bar3);
xmlDoc.removeChild(bar2);

Upvotes: 6

detroitpro
detroitpro

Reputation: 3913

I would convert it to json; I hate working with xml in javascript.

There are plugins that will handle the conversion for you.

http://www.fyneworks.com/jquery/xml-to-json/

http://plugins.jquery.com/project/xmlObjectifier/

Upvotes: 2

Related Questions