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

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

and what about changing values inside an element.
you can use all standard DOM manipulation functions, including setAttribute, etc. w3.org/DOM
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/

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.