messy
messy

Reputation: 915

Iterate over XML nodes and change properties

I have a big xml file with the following structure:

<items>
    <item>
        <a>id1</a>
        <b>foo</b>
        <c>1</c>
        <d>1</d>
        <e></e>
    </item>
    <item>
        <a>id2</a>
        <b>bar</b>
        <c>1</c>
        <d>1</d>
        <e>3</e>
    </item>
    <item>
        <a>id3</a>
        <b>fum</b>
        <c>1</c>
        <d>1</d>
        <e></e>
    </item>
</items>

I would like to set the value of e with a value which depends on the value of a. So if the item contains the value id1 for the property a, e should be set with 123, if the property a is id2 set it to 456 etc.

It's easy to use with a script language. I tried it with JavaScript (jQuery) in the dev tools of the Chrome browser but I was only able to read the values but not write them back. Maybe I'm just too tired... If anyone of you can help me which a script language of your choice (best would be you don't have to install anything) I would be glad!

Here is the small snippet I used so far:

$($.parseXML(xml)).find('chests_costs').children().each(function(i, o) {
    if($(o).find('a').text() == 'id1') {
        $(o).find('a').text('123')
    }
});

Upvotes: 0

Views: 64

Answers (1)

Anthony
Anthony

Reputation: 1581

You can grab each a element and each e element from the xml doc, loop through all a elements and use a switch statement to add textContent to the e elements.

var str = "<items><item><a>id1</a><b>foo</b><c>1</c><d>1</d><e></e></item><item><a>id2</a><b>bar</b><c>1</c><d>1</d><e>3</e></item><item><a>id3</a><b>fum</b><c>1</c><d>1</d><e></e></item></items>";

var xmlDoc = $.parseXML(str);
var $xml = $(xmlDoc);
var $a = $xml.find('a');		// find all a elements
var $e = $xml.find('e');		// find all e elements

console.log("xml string before: " + str);

for (var i = 0; i < $a.length; i++) {
    switch ($a[i].textContent) {
     case "id1":
  	 $e[i].textContent = 123;
      break;
    case "id2":
    	$e[i].textContent = 456;
      break;
    default:
    	break;
  }
}

function xmlToString(xmlData) { 

    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData);
    }
    return xmlString;
}

console.log("xml string after: " + xmlToString(xmlDoc));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Converted the xml to string to be viewable in the console. Took the function from here.

Upvotes: 1

Related Questions