i am receiving xml as a web response.
<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">
<s:Header/>
<s:Body>
<ProductIdResponse xmlns="http://example.org/">
<Product>123</Product>
<ProductIdResponse>
</s:Body>
</s:Envelope>
I am looking to extract value from xml using pure javascript and store it in variable. there are many example in stackoverflow but all are using DOM elements and jquery.
any help would be appreciated.
have a look here: XML Parser
you load the xml into an xml document, and then access the elements the same way you would on your page's document:
//initialize your xml for testing purposes
txt='<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
txt=txt+'<s:Header/>';
txt=txt+'<s:Body>';
txt=txt+'<ProductIdResponse xmlns="http://example.org/">';
txt=txt+' <Product>123</Product>';
txt=txt+'<ProductIdResponse>';
txt=txt+'</s:Body>';
txt=txt+'</s:Envelope>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var myProduct = xmlDoc.getElementsByTagName("Product")[0].innerHTML;
alert(myProduct);
If you dont want to parse the xml into DOM, you can alternatively retrieve the data using RegEx matching
check Here for a good RegEx tester where you can practice regex.
//initialize your xml for testing purposes
txt = '<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
txt = txt + '<s:Header/>';
txt = txt + '<s:Body>';
txt = txt + '<ProductIdResponse xmlns="http://example.org/">';
txt = txt + ' <Product>123</Product>';
txt = txt + ' <Product>Product 2</Product>';
txt = txt + '<ProductIdResponse>';
txt = txt + '</s:Body>';
txt = txt + '</s:Envelope>';
var myProducts = txt.match(/<Product>(.*?)<\/Product>/g);
myProducts.forEach(function(val, id) {
myProducts[id] = myProducts[id].replace(/(<([^>]+)>)/ig, "");
});
console.log(myProducts);
alert("2nd product is: " + myProducts[1]);
Related
Below is my ajax function which retrieves the data from servelt and shows it fine in the jps and the problem is every time a new ajax calls is submit the form just appends the data into the results received from previous calls, I need reset the current values stored in the table OrderResultContainer and then display it with new data.
I tried
document.getElementById("OrderResultContainer").reset = ();
but it's just reset the entire form data and not showing any data in the page.
function addData() {
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
var loading = document.getElementById("loading");
document.getElementById("loading").style.display = "";
document.getElementById("OrderResultContainer").style.display = "none";
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
xhttp.onreadystatechange=function() {
if ((xhttp.readyState == 4) && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
txt = "";
for (x in jsonorderdata) {
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
}
document.getElementById("loading").style.display = "none";
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
document.getElementById("divOrderResultContainer").style.display = "";
}
};
}else
console.log('Ajax call is failed');
}
Can anyone help me on how to reset the data in the table OrderResultContainer alone after a new ajax response received from servlet.
You append the received data to the previous with following code:
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
So if you change it like following you would have only new data:
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
It is kind of hard to see without the corresponding html but this looks like the problem:
document.getElementById("ViewOrderResultContainer").innerHTML =
document.getElementById("ViewOrderResultContainer").innerHTML + txt;
Your taking the innerHtml from the ViewOrderResultContainer and append the value from txt. If you do that more than once than it will keep growing. If you want to replace the text than replace it with
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
p.s. the given javascript is not valid
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
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 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'm starting off with js.
I want to fetch data from a server with xml. I wonder how to send a request as, and get an anser in xml through javascript functions.
It says I need a POST-Request and send an xml in the form:
<?xml version="1.0" encoding="UTF-8"?>
<ft>
<request clientId="123" apiName="api_search_location_stops_nearby" apiVersion="2.0">
<client clientId="123"/>
<requestType>api_search_location_stops_nearby</requestType>
<outputCoords>WGS84</outputCoords>
<fromCoordName>WGS84</fromCoordName>
<fromType>coords</fromType>
<fromWgs84Lat>48.22</fromWgs84Lat>
<fromWgs84Lon>16.39</fromWgs84Lon>
</request>
</ft>
To then get an xml answer. It has 2 or 3 nodes in it, which I'm interested in. From there on, it'll be no big deal.
It is all about a strange API from the vienna public transport company:
http://akirk.github.io/Wiener-Linien-API/
I basically want to get (open)data from them.
Here:
https://techscreen.tuwien.ac.at/node/794
I found a solution for php..
My try:
// Bare bones XML writer - no attributes
function xmlElement(name,content){
var xml
if (!content){
xml = '<' + name + '>' + '</' + name + '>'
}
else {
xml = '<'+ name + '>' + content + '</' + name + '>'
}
return xml
}
function sendRequest()
{
var xmlReq
xmlReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xmlReq = xmlReq + "<ft>";
xmlReq = xmlReq + "<request clientId=\"123\" apiName=\"api_get_monitor\" apiVersion=\"2.0\">";
xmlReq = xmlReq + "<client clientId=\"123\"/>";
xmlReq = xmlReq + xmlElement("requestType", "api_get_monitor");
xmlReq = xmlReq + xmlElement("monitor",
xmlElement("outputCoords", "WGS84") +
xmlElement("type","stop") +
xmlElement("name","60201040") +
xmlElement("year","2013") +
xmlElement("month","10") +
xmlElement("day","3") +
xmlElement("hour","8") +
xmlElement("minute","0") +
xmlElement("line") +
xmlElement("sourceFrom","stoplist") );
xmlReq = xmlReq + "</request>" + "</ft>";
text1.text = xmlReq;
var xhr = new XMLHttpRequest();
xhr.onload = handleRequest;
xhr.open("POST", "http://webservice.qando.at/2.0/webservice.ft"); // POST or GET
xhr.send(xmlReq);
// xhr.responseXML // this is allways null
}
function handleRequest(answer)
{
console.log(answer.responseType);
console.log(answer.responseXML);
}
The core points of my question: On my code, should there be GET or POST? Is the request built up to fit the style above (or do I need linebreaks or convert to a DOM xml thing)? How does the recieving thing work. Am I doing this right? Should the variable answer then contain the xml with the answer?
This code is somehow not working. I printed the xml-string to the console and it looks just like above (without linebreaks). But the handleRequest function doesn't print anything (it is not called at all).
Thanks in advance!
Looks like it was good allready.
I got the wrong clientID. That was basically it. Then there was just a small modification to make:
xhr.onreadystatechange = function(){ page.handleRequest(xhr); }
..to send the xmlHttpRequest over to the function. This worked for me.
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>";