7

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. :)

Yarin Miran
  • 3,241
  • 6
  • 30
  • 27

3 Answers3

6

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);
Josef Pfleger
  • 74,165
  • 16
  • 97
  • 99
2

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/

detroitpro
  • 3,853
  • 4
  • 35
  • 64
1

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.

Rakesh Pai
  • 26,069
  • 3
  • 25
  • 31