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
Related
I'm using Ajax/jQuery to pull in some content from an RSS feed, but it seems to be failing to read the content of an XML node with the name 'link'.
Here's a simplified version of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<channel>
<item>
<title>Title one</title>
<link>https://example.com/</link>
<pubDate>Mon, 12 Feb 2019</pubDate>
</item>
<item>...</item>
<item>...</item>
</channel>
</xml>
And the code I'm using:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('item', this.responseText).each(function(){
var thisPostData = {};
thisPostData.title = $(this).find('title').text();
thisPostData.link = $(this).find('link').text();
thisPostData.date = $(this).find('pubDate').text();
posts.push(thisPostData);
});
console.log(posts);
}
};
var posts = [];
xhttp.open('GET', 'https://example.com/rssfeed/', true);
xhttp.send();
You'll see I'm trying to add each 'item' to an object, and storing them inside the 'posts' array. 'Title' and 'pubDate' are stored fine but 'link' isn't.
The actual RSS feed in question contains a huge amount of extra data, all of which I can read except the 'link' nodes. Any suggestions why nodes called 'link' would act differently from all the others?
The problem is because you're attempting to parse XML as HTML. The <link> object in HTML is an inline element, not a block level one, so it has no textContent property for jQuery to read, hence the output is empty.
To fix this first read the XML using $.parseXML(), then put it in a jQuery object which you can traverse.
There's also a couple of things to note. Firstly you will need to remove the </xml> node at the end of the XML output as it's invalid and will cause an error when run through $.parseXML. Secondly you can use map() to build an array instead of manually calling push() on an array, and you can just return the object definition directly from that. Try this:
var responseText = '<?xml version="1.0" encoding="UTF-8"?><channel><item><title>Title one</title><link>https://example.com/</link><pubDate>Mon, 12 Feb 2019</pubDate></item><item><title>Title two</title><link>https://foo.com/</link><pubDate>Tue, 13 Feb 2019</pubDate></item></channel>';
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
console.log(posts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Lastly, you're using a rather odd mix of JS and jQuery. I'd suggest going with one or the other. As such, here's a full jQuery implementation with the AJAX request included too:
$.ajax({
url: 'https://example.com/rssfeed/',
success: function(responseText) {
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
// work with posts here...
}
});
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 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