Import XML with JavaScript function - javascript

I have a panel, that when clicked opens up and displays data. I would like to have the data come from a XML file.
The JavaScript function that I was using to display html text worked, so I was trying to use that function, but modify it to bring over the XML from another file.
The JavaScript function from the JS file:
function nameFunction () {document.querySelector("#collapse1> .panel-body").innerHTML = "Name works"};
The XML from the XML file
<dashboard>
<name>name goes here</name>
</dashboard>
The html file that calls the JS function:
<a data-toggle="collapse" href="#collapse1" onClick="nameFunction()" >Name</a>
Can the .innerHTML method be used for this task? If so, can someone provide an example?

function nameFunction () {
var xmlText = "<dashboard>"+
"<name>name goes here</name>"+
"</dashboard>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlText,"text/xml");
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
hope this can help you ! (this works)

function nameFunction (){
var xhttp;
if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object.
//code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "data.xml", false);
xhttp.send();
var xmlDoc = xhttp.responseXML;
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
this works in firefox,(not in chrome - chrome doesn't have XMLHttpRequest API I guess)
so now you can parse xml file

you can import files using script tag.
<script id="xml" type="notjs" src="XX.xml"></script>
var xml = document.getElementById("xml");
Is this what you want?

Related

javascript json parse from URL

UPDATED:
I'm trying to parse a response from a URL but have no idea if I'm doing it correctly.
The URL returns the following JSON:
{"make":"truck","date":"23 July 2009","colour":"pink"};
If i replace var newtext = xhttp.responseText; with
var newtext = '{"make":"truck","date":"23 July 2009","colour":"pink"}';
it works but as soon as i go back to the xhttp.responseText it just shows a blank page.
The code I'm using is:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
xhttp.open("GET", "https://url.com", false);
xhttp.send();
var newtext = xhttp.responseText;
var obj = JSON.parse(newtext);
document.getElementById("demo").innerHTML =
obj.make + "<br>" +
obj.colour + "<br>" +
obj.date;
</script>
</body>
</html>
You haven't defined your variable xhttp, but you are trying to call functions on it. This is resulting in the Uncaught ReferenceError error and causing the rest of the code not to run. To create an XMLHttpRequest object as you appear to be trying to do, put this at the top of your script.
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// the object actually exists here now so the functions can be called on it
xhttp.open("GET", "https://url.com", false);
xhttp.send();
...
Then you can continue on with the rest of your code, assured that your xhttp object has been initialized.
I don't normally recommend using w3schools, but the above code was copied from http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

Reading XML from URL using Javascript

I am writing code to retrieve some part of an xml document. I am using Wolfram API (I am registered and I have an AppID.). So if I save the xml file locally after I execute the search command (variable "url" below),it works perfecly (if I have xmlDoc.load("query2.xml") where the xml is savedd in query2.url). However, I want to put a url instead, and get them on the fly rather than save the xml. I tried xmlDoc.load(url) but that didn't work, and after researching I found a function that's supposed to help retrieve this xml data from a tutorial website, but that didn't work either (it doesnt display anything on the page). How can I get the xml given a url?
Thanks in advance!
<body>
<div id="container" style="background-color:yellow"></div>
<script>
//load xml file
var url = "http://api.wolframalpha.com/v2/query?input=distance%20from%20london%20to%20california&appid=xxx";
if (window.ActiveXObject){
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false; //Enforce download of XML file first. IE only.
}
else if (document.implementation && document.implementation.createDocument)
var xmlDoc= document.implementation.createDocument("","doc",null);
if (typeof xmlDoc!="undefined") {
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc.load(loadXMLDoc(url));
//xmlDoc.load("query2.xml");
}
else {
}
//Regular expression used to match any non-whitespace character
var notWhitespace = /\S/
function getnumber(){
//Cache "messages" element of xml file
var msgobj=xmlDoc.getElementsByTagName("plaintext")[1]
//REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla
for (i=0;i<msgobj.childNodes.length;i++){
if ((msgobj.childNodes[i].nodeType == 3)&&
(!notWhitespace.test(msgobj.childNodes[i].nodeValue))) {
// that is, if it's a whitespace text node
msgobj.removeChild(msgobj.childNodes[i])
i--
}
}
//Get answer and display it in DIV:
document.getElementById("container").innerHTML=
xmlDoc.getElementsByTagName("plaintext")[1].childNodes[0].nodeValue
}
if (typeof xmlDoc!="undefined"){
if (window.ActiveXObject) //if IE, simply execute script (due to async prop).
getdaily()
else //else if NS6, execute script when XML object has loaded
xmlDoc.onload=getnumber
}
</script>
</body>

Can't create an XML node using Javascript

I am trying to create a simple XML node with text "New node!"
var xmlDoc = loadXMLDoc("myFile.xml");
var newElem = xmlDoc.createElement("elem");
newElem.innerHTML = "New node!";
Where loadXMLDoc() is
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
But the code does not work. I expect the XML file to have a new node "<elem>" with "New node!" in it, but it was still the same. I have no idea why. There were no error messages.
How do I get my code to work?
Your code is creating a new element, but you are not appending it to the XML.
See the example here: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement#Example

DOMParser.parseFromString fails with XML5619: Incorrect document syntax

I have this javascript function that gets an xml file from a web site:
function getCCDfromHV() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xml = xmlhttp.responseText;
document.getElementById("uploadResponse").innerHTML=xml;
xmlDom = createXmlDOM(xml);
}
}
xmlhttp.open("GET","../HVRawConnectorPHP/demo_app/GetCCDfromHV.php",true);
xmlhttp.send();
}
The xml is retrieved ok as I can see from the dump to .innerHTML. But createXmlDOM's parseFromString fails with "XML5619: Incorrect document syntax" as shown below:
function createXmlDOM(xml) {
console.log('createXmlDOM: the first 255 chars=' +xml.substring(0,255));
if (window.DOMParser){
var parser=new DOMParser();
xmlDom=parser.parseFromString(xml,"text/xml"); //fails with XML5619: Incorrect document syntax.
}
else { // Internet Explorer
xmlDom=new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async=false;
xmlDom.loadXML(xml);
}
return xmlDom;
}
But if I copy the .innerHTML text and paste it into an editor and save it as a text file, load that file using FileReader, then send that text to createXmlDOM, it works fine!
So somehow the act of cut and pasting or file writing and reading does some kind of translation that makes it acceptable to parseFromString. Is there a way do do it without saving and reloading a file? It seems to be failing on the first character which is a '&' because the first char is really '<' but html changes that to &lt whereas loading it from text file doesn't.
I finally figured it out. The xml needs to be html decoded. I added the following function:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Which I found from here:
http://css-tricks.com/snippets/javascript/unescape-html-in-js/

getElementsByTag not working

Hi so I have a XML document in a folder on my desktop, I am trying to read out all the elements with the tag name "cuisine".
Here is my code:
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","data.xml", false);
xmlhttp.send()
xmlData = xmlhttp.responseXML;
cuisineList = xmlData.getElementsByTagName("cuisine");
document.getElementById("test").innerHTML = cuisineList.length;
When I print out the length of the cuisineList it says its zero.
Here is my XML document:
<?xml version="1.0" encoding"ISO-8859-1"?>
<food>
<cuisine type="Chinese">
</cuisine>
<cuisine type="Indian">
</cuisine>
</food>
I think you have an error in your document (there is a missing '=' in the encoding attribute).

Categories

Resources