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();
Related
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
I got a question regarding passing the value of the select option to my XML parser. First look at my code:
HTML
<table id="ProfileList">
<tr>
<td>session</td>
<td>timestamp</td>
</tr>
</table>
<select>
<option value="none">--select user--</option>
<option value="user20">user20</option>
<option value="user30">user30</option>
<option value="user40">user40</option>
<option value="user50">user50</option>
</select>
As you can see I have a select box with 5 options were only the last four are important.
Javascript
$('select').change(function() {
var user = $(this).val();
alert($(this).val());
//Sample XML
var user20 = "<?xml version='1.0' ?><results><row><session>21</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>";
var user30 = "<?xml version='1.0' ?><results><row><session>26</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>";
//Parse the givn XML
var xmlDoc = $.parseXML( user );
var $xml = $(xmlDoc);
var $row = $xml.find("row");
$row.each(function(){
var session = $(this).find('session').text(),
time = $(this).find('time').text();
$("#ProfileList" ).append('<tr><td>' +session+ '</td>' + '<td>' +time+ '</td></tr>');
});
});
What I want is that the value of my select option is used as input for my XML parser. If I run this code, then I will get an error that the XML is invalid.
To clarify: If I set a fixed value then it works:
var xmlDoc = $.parseXML( user20 );
But if I want to set it variable it does not work:
var xmlDoc = $.parseXML( user );
Can anyone tell me why this is and perhaps how I could solve this?
DEMO CAN BE FOUND HERE
I would use an object containing the XML samples and access each XML by its property name of the object, see http://jsfiddle.net/3po6xgmt/ which does
$('select').change(function() {
var user = $(this).val();
alert($(this).val());
//XML samples
var samples = {
user20 : "<?xml version='1.0' ?><results><row><session>21</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>",
user30 : "<?xml version='1.0' ?><results><row><session>26</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>"
};
//Parse the given XML
var xmlDoc = $.parseXML( samples[user] );
var $xml = $(xmlDoc);
var $row = $xml.find("row");
$row.each(function(){
var session = $(this).find('session').text(),
time = $(this).find('time').text();
$("#ProfileList" ).append('<tr><td>' +session+ '</td>' + '<td>' +time+ '</td></tr>');
});
});
I am building an app with gae, and using the channel api.
String message ="<data><title>newMessage</title><message>Hello</message></data>";
channelService.sendMessage(new ChannelMessage(user,message));
This string is sent from the java servlet, and on the front end i want to parse it with jquery. This is what i did, but it doesn't work.
function onSocketMessage(message) {
var xml = $.parseXML(message.data),
$xml = $( xml ),
$title = $xml.find('title');
if($title == "newMessage"){
alert($xml.find('message'));
}
}
This is the javascript code which actually works fine.
var messageXML = ((new DOMParser()).parseFromString(message.data, "text/xml"));
var title = messageXML.documentElement.getElementsByTagName("title")[0].firstChild.nodeValue;
if(title == "newMessage"){
alert(messageXML.documentElement.getElementsByTagName("message")[0].firstChild.nodeValue);
}
function onSocketMessage(message) {
var xml = $.parseXML(message.data),
$xml = $( xml ),
$title = $xml.find('title');
if($title.text() == "newMessage"){
alert($xml.find('message'));
}
}
You should be giving .text(), I guess you missed that in this line if($title.text() == "newMessage").
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
??? :_)
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