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
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 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();
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