4 Replies - 534 Views - Last Post: 06 June 2018 - 12:13 PM

#1 yumyum   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 05-March 16

I am trying to pull data from xml file using javascript

Posted 06 June 2018 - 08:36 AM

I am trying to pull data from an xml file using javascript. I have found a working example however it stores the data as a string inside the script tags using concatenation Link to example. Instead I want to separate my concerns. index.html, script.js, and file.xml. I am unsure what to do or try next. If you know where I can find a working example or suggest what I can change to accomplish this will be greatly appreciated.

HTML
<!html doctype>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
	<h2>XMLHttpRequest</h2>
	<p id="address"></p>
	<span id="num"></span> <span id="street"></span><br /> <span id="city"></span>, <span id="state"></span> <span id="zip"></span>
</body>
<script type="text/javascript">
const xhr = new XMLHttpRequest();



xhr.onreadystatechange = function(){
	if (xhr.readyState == 4){
		if (xhr.status == 200){
			document.getElementById('address').innerHTML = xhr.responseText;
			
			
			document.getElementById("num").innerHTML=
			xmlData.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;
			document.getElementById("street").innerHTML=
			xmlData.getElementsByTagName("street")[0].childNodes[0].nodeValue;
			document.getElementById("city").innerHTML=
			xmlData.getElementsByTagName("adminName2")[0].childNodes[0].nodeValue;
			document.getElementById("state").innerHTML=
			xmlData.getElementsByTagName("adminCode1")[0].childNodes[0].nodeValue;
			document.getElementById("zip").innerHTML=
			xmlData.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
			
		}
		
		if (xhr.status == 404){
			console.log('File or resource not found');
		}
	}
};
	xhr.open('get', 'address.xml', true);
	xhr.send();
	xmlData = xhr.responseXML;
	xmlData = (new DOMParser()).parseFromString(xhr.responseText, 'text/xml');
	

</script>
</html>




XML
<?xml version="1.0" encoding="UTF-8"?>
<address>
 <street>Kansas Ave</street>
  <mtfcc>A9850</mtfcc>
  <streetNumber>89765</streetNumber>
  <lat>89.326</lat>
  <lng>565.256</lng>
  <distance>12.53</distance>
  <postalcode>90210</postalcode>
  <placename>Manhattan</placename>
  <adminCode2>555</adminCode2>
  <adminName2>Cain</adminName2>
  <adminCode1>777</adminCode1>
  <adminName1>Madhan</adminName1>
  <countryCode>MX</countryCode>
 </address>



Is This A Good Question/Topic? 0
  • +

Replies To: I am trying to pull data from xml file using javascript

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4219
  • View blog
  • Posts: 13,353
  • Joined: 08-June 10

Re: I am trying to pull data from xml file using javascript

Posted 06 June 2018 - 08:55 AM

With XMLHttpRequest.responseXML you already get a ready XML DOM object (that makes the use of DOMParser superfluous).
Was This Post Helpful? 1
  • +
  • -

#3 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4219
  • View blog
  • Posts: 13,353
  • Joined: 08-June 10

Re: I am trying to pull data from xml file using javascript

Posted 06 June 2018 - 09:00 AM

Note: xmlData.getElementsByTagName("street")[0].childNodes[0].nodeValue can be simplified to xmlData.getElementsByTagName("street")[0].textContent
Was This Post Helpful? 1
  • +
  • -

#4 yumyum   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 05-March 16

Re: I am trying to pull data from xml file using javascript

Posted 06 June 2018 - 10:29 AM

I now have a working example. Thanks to all who replied. I appreciate your help and this website! Here is the example so others can learn from it too. JS Example

HTML
<!html doctype>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
	<h2>XMLHttpRequest</h2>
	<div id="output"></div>
</body>
<script type="text/javascript">

	function init(){
	
		var xhttp = new XMLHttpRequest();
		xhttp.onreadystatechange = function (){
			if (this.readyState ==4 && this.status == 200){
				console.log(this.responseXML);
				var schools = this.responseXML.getElementsByTagName("school");
				var strOut = "<ul>";
				for(i=0; i<schools.length; i++){
					var name = schools[i].getElementsByTagName("name")[0].innerHTML;
					var web = schools[i].getElementsByTagName("web")[0].innerHTML;
					strOut += "<li><ahref='"+web;
					strOut += "' target='_blank'>" + name + "</a></li>";
			}
			strOut += "</ul>";
			document.getElementById("output").innerHTML = strOut;
		}
	
	};
	
	xhttp.open('get', 'myXML.xml', true);
	xhttp.send();
	}
	window.onload = init;

</script>
</head>



XML
<?xml version="1.0" encoding="UTF-8"?>
	<sites>
		<school>
			<name>Middle Georgia State University</name>
			<web>http://www.mga.edu</web>
		</school>
		<school>
			<name>Columbus State University</name>
			<web>http://www.columbusstate.edu</web>
		</school>
		<school>
			<name>University of Georgia</name>
			<web>http://www.uga.edu</web>
		</school>
	</sites>


Was This Post Helpful? 0
  • +
  • -

#5 ge∅   User is offline

  • D.I.C Lover

Reputation: 194
  • View blog
  • Posts: 1,192
  • Joined: 21-November 13

Re: I am trying to pull data from xml file using javascript

Posted 06 June 2018 - 12:13 PM

Hello,

edit. gee, I must be tired I though you had written this code and created the video XD
I guess it can still be useful.

I think you should have separated the AJAX call, the data extraction and the presentation (same argument of separation of concerns, as well as modularity because you can keep your ajax and presentation modules and swap the extraction module as needed).

I'm showing you another way to do it with modules. You will note that the extractXML function is decoupled from your dataset. Of course, it won't convert any arbitrary XML to JSON, but I wanted you to see how it can be though of more generally. The renderData function could also be decoupled if you had a configuration JSON file, for example, telling it how to interpret the data, or you could use (or write, it's not complicated) a simple templating system. But this would start to complexify the script for no good reason. I have chosen another way to generate the HTML for the sake of educational value, there are other ways (DOM for example), but as you can tell I like to use map and forEach.

function ajax(url, callback) {
  var xhr = new XMLHttpRequest();
  if (callback) xhr.addEventListener("load", callback);
  xhr.open('GET', url, true);
  xhr.send();
}

function extractXML(xml) {
  return [].map.call(xml.documentElement.children, function (entry) {
    var content = {};
    [].forEach.call(entry.children, function (node){
      content[node.nodeName] = node.textContent
    });
    return content;
  });
}

function renderData(data) {
  return "<ul>" + data.map(function (entry) {
    return "<li><a href='" + entry.web + "'>"+ entry.name +"</a></li>"
  }).join("") + "</ul>"
}

ajax("myXML.xml", function () {
  document.getElementById("output").innerHTML = renderData( extractXML(this.responseXML) );
});



I've watched your video and I would like to argue that CSV files often have in the first line the titles of each column, so with a little bit of Javascript you can get any cell based on the column title and entry index, just as you would do with a table in a database. I find that CSV files actually make quite good portable filesystem readonly relational databases that you can view and edit in OpenOffice (but I'm a lazy graphic designer so this explains that).

This post has been edited by ge∅: 06 June 2018 - 12:33 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1