views:

156

answers:

3

Hello,

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

+2  A: 

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
+4  A: 

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
and what about changing values inside an element.
Yarin Miran
you can use all standard DOM manipulation functions, including setAttribute, etc. http://www.w3.org/DOM/
Josef
+1  A: 

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