Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 380
Yarin Miran Avatar asked Jul 05 '09 17:07

Yarin Miran


People also ask

Can JavaScript parse XML?

XML parsing in JavaScript is defined as it is one kind of package or library of the software which provides an interface for the client applications to work with an XML document and it is used in JavaScript to transform the XML document into readable form, nowadays in many browsers, the XML parser is already available ...

What is DOM parser in XML?

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document . You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.

What is JS XML?

XML stands for eXtensible Markup Language. XML is a markup language much like HTML. XML was designed to store and transport data.


1 Answers

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);
like image 144
Josef Pfleger Avatar answered Oct 02 '22 20:10

Josef Pfleger