John Adams
John Adams

Reputation: 21

Using jQuery to set values in an XML string

I receive the following XML-like string via an $.ajax() get. Because it's not valid I cannot use dataType:'xml' or parse with $.parseXML(). Using the xml as a string though and using jQuery to traverse it seems to work ok. I can use the find() method to read the attributes but I cannot seem to set a value. (I can only get the XML, it is provided by another dept and I have no way of changing it.)

TLDR: Need to manipulate an xml string. Add user, password, and type values so it can be sent back to the server.

var xml = '<attrs xmlns="http://www.blah.com/abc/wxyz"><attr name="user" type="string"/><attr name="password" type="string"/><attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr></attrs>';

/*
<attrs xmlns="http://www.blah.com/abc/wxyz">
  <attr name="user" type="string"/>
  <attr name="password" type="string"/>
  <attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr>
</attrs>
*/

// The following works fine. I get the possibilites, split them, and add them to a form:
$.each( $(xml).find('attr[possibilities]').attr('possibilities').split(','), function(index,value){
  options += '<option value="'+value+'">'+value+'</option>';
});

// I have tried the text(), prop(), and attr() methods. From what I've read you are supposed to use prop() instead of attr for setting values, but I tried attr anyway.
$(xml).find('attr[name=user]').attr( 'textContent', 'TEST' );
$(xml).find('attr[name=user]').text( 'TEST' );  
$(xml).find('attr[name=user]').prop( 'textContent', 'TEST' );

// After attempting attr, text, and prop, the textContent property shows nothing (not undefined):
console.log( 'textContent ' + $(xml).find('attr[name=user]').prop('textContent') );

I'm relatively new at this, so it's possible my selector is just wrong. Any help is appreciated. Thanks in advance.

Upvotes: 2

Views: 5192

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Use $.parseXML to allow you to manipulate the xml with jQuery

Example:

var $xml=$($.parseXML( xml));
 /* create a new xml node*/
 var testAttr=$( '<attr name="test"></attr>');
  /* append node to xml*/
 $xml.find('attrs').append(testAttr);
 /* change an attribute in xml*/
 $xml.find('attr[name="user"]').attr('type', 'Dynamically changed');

Demo: http://jsfiddle.net/Ut5Gg/

Upvotes: 0

dvd
dvd

Reputation: 1034

Every time you call $(xml) you are creating a new dom object based on the original string.

Try this instead:

 j = $(xml);
 j.find('attr').attr('foo', 'bar');
 console.log(j.html());

now you parse the xml string only once and update the resulting node.

Upvotes: 4

Related Questions