How to modify XML with JQuery - javascript

I am trying to modify a status flag in an XML structure using Javascript. Using examples found on the internet I believe this should work:
test = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>" +
"<resultaat>" +
"<type>6</type>" +
"<status>I</status>" +
"<start_datum>2012-06-16 00:00:00</start_datum>" +
"<eind_datum></eind_datum>" +
"</resultaat>"
To change the content of the status field:
$(test).find("status").text("D")
The result is however that test is not modified and still contains the old status I
Thanks for the answers
The correct insight is that you need to convert to an XMLObject first and modify this.
Below is how I ended up doing it:
/* Convert Text to XML Object */
doc = $.parseXML(test)
/* Change the fields required */
$(doc).find('status').text('D')
/* Back to Text */
str = (new XMLSerializer()).serializeToString(doc);

Use jQuery.parseXML()
<p id="someElement"></p>
<p id="anotherElement"></p>
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
/* append "RSS Title" to #someElement */
$( "#someElement" ).append( $title.text() );
/* change the title to "XML Title" */
$title.text( "XML Title" );
/* append "XML Title" to #anotherElement */
$( "#anotherElement" ).append( $title.text() );

you need to write code something like this...
test = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>" +
"<resultaat>" +
"<type>6</type>" +
"<status>I</status>" +
"<start_datum>2012-06-16 00:00:00</start_datum>" +
"<eind_datum></eind_datum>" +
"</resultaat>";
def = $(test).find("status").text("D");
console.log(def);
To make it work....

Mmmmm, this answers works... but not allways. I'm using an old webkit version wich is bundled inside Tidesdk and i have some weird problems:
$(xml).find("whatever").append("<however></however>");
// doesn't modify xml
$("<however></however>").appendTo($(xml).find("whatever"));
// does modify xml
??? :_)

Related

jQuery - Get Content from an XML Page and save to a variable

I am trying to get the content of an XML Element into a variable:
<ContactPresence>
<ContactUri>test.com</ContactUri>
<PresenceState>offline</PresenceState>
</ContactPresence>
How can I get "PresenceState" into a variable?
With jQuery, you can use parseXML
var xml = "<ContactPresence><ContactUri>test.com</ContactUri<PresenceState>offline</PresenceState></ContactPresence>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$node = $xml.find( "PresenceState" );
var presenceState = $node.text(); // Should contain offline

Issues parsing cross domain xml with jQuery

I found a solution here on SO for retrieving cross domain xml files, however I am unable to parse the returned data. I also need to set a timeout function on this in order to keep it refreshing - it is price/voulume data.
//the remote xml
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$price = $xml.find( "Currency Value");
$( "#data" ).append( $price.text() );
console.log(xml);
});
a simple fiddle is here
it appears in the console under #document, as a string, I dont know if that is correct or not. It seesm like that could be an issue as well as the tag names having spaces in them e.g. "BuyPrice Value"
Ive read several other questions here and unfortunately I don't think the back end developer will deliver in jsonp, which would alleviate a lot of this. Also, what would be the best method to get this to refresh every XX minutes? Any advice is greatly appreciated.
First, you have to deal with the fact that you have an xml document inside your xml document.
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( $(xml).find("string").text() ),
Then you want to get the Currency node's Value attribute.
$xml = $( xmlDoc ),
$price = $xml.find("Currency");
$( "#data" ).append( $price.attr("Value") );
Final Result:
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( $(xml).find("string").text() ),
$xml = $( xmlDoc ),
$price = $xml.find("Currency");
$( "#data" ).append( $price.attr("Value") );
http://jsfiddle.net/F52a5/1/
Two ways of refreshing it:
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
setInterval(function(){
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML($(xml).find("string").text()),
$xml = $(xmlDoc),
$price = $xml.find("Currency");
$("#data").append($price.attr("Value"));
});
},30*1000);
Or, the preferred method:
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
function getNewData() {
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML($(xml).find("string").text()),
$xml = $(xmlDoc),
$price = $xml.find("Currency");
$("#data").append($price.attr("Value"));
setTimeout(getNewData,30*1000);
});
}
getNewData();

How to get the nodes inner text in java script?

I have a string of XML format. As shown below:
<gt>
<st>sample1</st>
<tt>sample2</tt>
<tt>sample3</tt>
</gt>
I need to get the node value in Java script file. How can I get the value?
Use .parseXML().
var xmldom = $.parseXML('<gt><st>sample1</st><tt>sample2</tt><tt>sample3</tt></gt>');
console.log($(xmldom).find('gt *'));
This will find all nodes under <gt>.
Try this code:
var xml = "<gt><st>sample1</st><tt>sample2</tt><tt>sample3</tt></gt>",
xmlDoc = $.parseXML(xml),
$xml = $( xmlDoc ),
$st = $xml.find( "st" );
alert( $st.text() );
See the js fiddle example

Access XML through JavaScript

I have a XML file and am trying to pull out data out of it. The XML file looks like this
<doc>
<str name="name">Rocky</str>
<str name="Last_name">balboa</str>
<str name="age">42</str>
<str name="sex">M</str>
<str name="dob">2012-09-09</str>
</doc>
<doc>... </doc>
<doc>... </doc>
<doc>... </doc>
My .ajax call goes like this...
$.ajax({
type : "GET",
url : "my.xml",
dataType : "xml",
success : function(data) {
$(data).find('doc').each(function() {
alert("i was here");
var u1 = $(this).find('name').text();alert(u1);
var u2 = $(this).find('last_name').text();
var finale1 = u1 + "/" + u2;
var dt = $(this).find('dob').text();
var dt1 = dt.substr(0,4);
var desc = $(this).find('age').text();
alert("i am here");
});
}
});
What am I doing wrong over here? Can anyone please point out.
When you are trying to select the following tag:
<str name="name">Rocky</str>
Instead of using $(this).find('name') you should use $(this).find('str[name="name"]')
This error appears many times, for each str tag.
You should parse your xml before using it (no need to do it if your ajax call returns xml).
Pay attention to:
Tag names: you look for a <document> element whereas you have <doc>
elements
Attributes and tag are different things. find('name') looks for a
tag, not for a name attribute:
See here for a working example (My xml is a local string, but you can easily adapt the script) and here for parseXML documentation and xml usage examples.
var xml = "<doc><str name=\"name\">Rocky</str><str name=\"sex\">M</str><str name=\"dob\">2012-09-09</str></doc>",
xmlDoc = $.parseXML( xml ),
xml = $( xmlDoc ),
name = xml.find( "str[name='name']" );
alert (name.text());
You can use Jquery parse xml to navigate the dom e.g. http://jsfiddle.net/qd2xY/
var xml = '<docs><doc><str name="name">Rocky</str><str name="Last_name">balboa</str><str name="age">42</str><str name="sex">M</str><str name="dob">2012-09-09</str></doc><doc><str name="name">Rocky1</str></doc></docs>';
$(document).ready(function(){
xmlDoc = $.parseXML(xml);
$xml = $( xmlDoc ),
$xml.find('doc').each(function(){
alert($(this).find('str[name="name"]').text())
})
})
your xml is not well formed, also never use the DOM traversal methods to parse the XML it becomes browser dependent, always use some sort of standard parser e.g. in jquery you can use .parseXML, in you success call back try
success : function(data) {
var xml=data;
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$.each($xml.find("str"),function(){
alert($(this).attr("name"));
});
}
DEMO

How to parse XML string value using jQuery?

I am new to jquery. I am trying to parse xml string using jquery. I have found one sample:
$(function () {
$.get('data.xml', function (d) {
var data = "";
var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
var endTag = "</tbody></table>";
$(d).find('url').each(function () {
var $url = $(this);
var link = $url.find('link').text();
var name = $url.find('name').text();
data += '<tr><td>' + name + '</td>';
data += '<td>' + link + '</td></tr>';
});
$("#content").html(startTag + data + endTag);
});
});
In this case, I am able to parse and fetch the values from xml file, but now what I am looking for is instead of reading file from a URL, I want to read the xml from string. Say, instead of data.xml I want to parse string which consists of well formed xml.
Does anyone have any idea about this ?
Thanks in advance
Edit :
I tried a sample code on following xml;
<?xml version="1.0" encoding="utf-8" ?>
<Urls>
<url>
<name>google</name>
<link>www.google.com</link>
</url>
<url>
<name>aspdotnetcodebook</name>
<link>http://aspdotnetcodebook.blogspot.com</link>
</url>
</Urls>
When I try this on xml file, everything works fine. But when I switched to string, it returns nothing for link attribute. I am calling it as;
$(function() {
var data = $('<?xml version="1.0" encoding="utf-8" ?><Urls><url><name>google</name><link>www.google.com</link></url><url><name>aspdotnetcodebook</name><link>http://aspdotnetcodebook.blogspot.com</link></url></Urls>');
alert(data);
doWhateverItIsYourDoing(data);
});
I am unable to diagnose why this is happening.
Just pass the string directly?
function doWhateverItIsYoureDoing(xml) {
var data = "";
var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
var endTag = "</tbody></table>";
$(xml).find('url').each(function() {
var $url = $(this);
var link = $url.find('link').text();
var name = $url.find('name').text();
data += '<tr><td>' + name + '</td>';
data += '<td>' + link + '</td></tr>';
});
$("#content").html(startTag + data + endTag);
}
your .get could be rewritten as:
$.get('data.xml',doWhateverItIsYoureDoing );
and if you have xml in a string already, then
var data = "<?xml version=\"1......";
doWhateverItIsYoureDoing(data);
Just put that well-formed XML string into a jQuery object:
var xml = "<?xml version=\"1.0\"?><Dialog><Adam Emotion=\"strong\">I love you!</Adam><Eva Emotion=\"low\">I love you, too!</Eva></Dialog>";
access with
alert($(xml).find('Adam').text());
or
alert($(xml).find('Adam').attr('Emotion'));
put the the XML string into javascript variable
var xmlString = $(‘<?xml version=”1.0″?><Customers><Customer Name=”Allan Border” Age=”26″ ContactNumber=”004416165245″ Address=”Unit # 24 East London” City=”London” Country=”England”></Customer><Customer Name=”Jennifer” Age=”28″ ContactNumber=”004416165248″ Address=”Unit # 28 West London” City=”London” Country=”England”></Customer></Customers>’);
Now you can parse the XML as iterate through each of the customer node…
$(xmlString).find("Customer").each(function () {
var customerName = $(this).attr("Name");
var age = $(this).attr("Age");
var contactNumber = $(this).attr("ContactNumber");
var address = $(this).attr("Address");
var city = $(this).attr("City");
var country = $(this).attr("Country");
});
Note that to properly parse any type of XML file, you want to use the parseXML() function as in:
var xml_jquery_object = jQuery.parseXML(xml);
When you do as presented in the other answers:
var html_jquery_object = jQuery(xml);
you ask jQuery to parse HTML and not XML. The big difference is that HTML removes some tags (body, html, head...) and expects certain tags to be empty (br, hr, ...). So it is likely to break the parsing of your XML file if it somehow includes such tags.
xml can be a direct string as well, of course. The AJAX .get() function returns a string to your function anyway. (The better .ajax() function can return an XML object directly.) So you may define any XML code in that variable as in:
xml = "<?xml version='1.0'?><test>...</test>";

Categories

Resources