Pulling XML Data using JavaScript - javascript

I'm trying to dispay the one node e.g. "title" on a internal html page but I need it to pull the data from an XML document that is saved on my Desktop but it doesn't seem to be finding the XML document. I'm not to sure what to add or how to combat this problem? Any help would be much appreciated! Many thanks
var parser, xmlDoc;
var text = loadXMLDoc("/Desktop/test.xml");
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

First of all you can't access any files from the absolute path of your system due to security reasons. you must need to upload file at first place, there after you can process the XML content.
follow link below tried to create small snippet for you.
HTML:
<div>
<label id="txtFileInfo"></label>
<input id="xmlFile" type="file">
</div>
JS:
(function($){
$('#xmlFile').unbind('change')
.bind('change', function(e){
if(this.files.length > 0){
var file = this.files[0];
if(file.type == 'text/xml'){
setTimeout(function(){
console.log('Reader');
var reader = new FileReader();
reader.addEventListener('load', function(){
console.log(reader.result);
parser = new DOMParser();
xmlDoc = parser.parseFromString(reader.result, file.type);
console.log(xmlDoc);
});
reader.readAsDataURL(file);
}, 100);
}
// $('#txtFileInfo').text('Type: '+ file.type);
}
});
})($);
https://codepen.io/smtgohil/pen/gGWoRe
All the best.

Related

selecting a file using location url instead of input file in html5 filereader for javascript

i want to give the file location url for the code to get my file instead of using input file in html part , to pass the file to the code
the code pasted below works if i use " input type= "file" " to get the file, but if i use url (like below) it gives a error
fileInput1.addEventListener is not a function
at window.onload
here is the code
window.onload = function() {
var z ="C:/Users/akash/Desktop/riidl/UTham.txt"
var fileInput1 = z;
if (fileInput1){
fileInput1.addEventListener('change', function(e) {
var file = fileInput1.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
spamdata=reader.result;
document.getElementById('here').onclick = console.log(spamdata);
}
reader.readAsText(file);
}
});
}
}
Accessing local files is not allowed in JavaScript for security purposes.
Pl refer to this answer for more details.
https://stackoverflow.com/a/372333/3626796

I would like to load a list of urls to a var in any browsers' dev console (JavaScript)

I have a .txt file on my hard drive containing lots of URLs structured like this:
http://url1.com/
http://url2.com/
.
.
.
I want to load them to a var in Firefox's/Chrome's/IE's dev console so that it would be a vector of strings. I plan to visit these pages with a for loop. How can this be done?
<script>
var urls = [
'http://url1.com/',
'http://url2.com/'
];
</script>
You can generate this snippet with code or just have your file export a global variable and then load it via tags.
You can read a file via JavaScript from the page. You cannot upload a file to the developer's console.
I then modified the code bellow a bit to help you further. I added a scrape function that will help you request each URL one at a time.
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
function scrape(urls) {
url = urls.shift()
$.get(function (url) {
// get the url data here
scrape(urls);
});
}
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
scrape(reader.result.split("\n"));
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Modified version of:
Read a local text file using Javascript
The only way di make your JavaScript aware of local files is to HTTP GET them.
So probably you have to put your file somewhere handy in the project folder and procees with an AJAX request.
var httpRequest;
function makeRequest() {
httpRequest = new XMLHttpRequest();
request.open("GET", "files/url.txt", false);
request.send(null);
saveArray(request.responseText);
}
var array = [];
saveArray(string){
array = string.split("\n")
}
You can get the contents of the file to show up in the Console with the below snippet.
var file="file://C:/FileName.txt";
function read(file)
{
var File = new XMLHttpRequest();
File.open("GET", file, false);
File.onreadystatechange = function ()
{
if(File.readyState === 4)
{
if(File.status === 200 || File.status == 0)
{
var Text = File.responseText;
console.log(Text);
}
}
}
File.send(null);
}
I found a simple but not very elegant workaround for the issue. I just copy and paste the list into a var definition. I don't have to do this often, so it is kind of okay.

How to read a text file saved on my computer using javascript

I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
At first, you need to use a input[type=file] to get a File.
<input type=file id=file/>
<div id=result></div>
And then use FileReader to read file to target format, just like base64, text, buffer.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.
<!DOCTYPE html>
<html>
<head>
<script>
function OnFileLoad() {
var file = document.getElementById("FileReader").files[0];
var textType = /text.*/;
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
</script>
</head>
<body>
<input type="file" id="FileReader" onchange="OnFileLoad()" />
<div id="FileContent">Your content will appear here</div>
</body>
</html>
In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here
<!DOCTYPE html>
<html>
<head>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
var fileDisplayArea = document.getElementById("FileContent");
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText;
}
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
rawFile.send(null);
}
readTextFile("file:///C:/Users/t0423/Desktop/test.js")
</script>
</head>
<body>
<div id="FileContent">Your content will appear here</div>
</body>
</html>

Using FileReader & DOMParser in AngularJS

I have a user uploaded file using AngularJS and like to manipulate the file contents using XML. However, I have a difficulty in the DOMParser recognising the text file.
index.html
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
app.js
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
reader = new FileReader();
reader.onload = function() {
showout.value = this.result;
txtFile = showout.value;
console.log(txtFile);
};
reader.readAsText(file);
parser=new DOMParser();
xmldoc = parser.parseFromString(txtFile,"text/xml");
console.log(xmlDoc);
In this example, the txtFile is correctly printed to the console, within the Reader.onLoad. However, xmlDoc shows as undefined.
I should I be referencing the file and converting it so that it can be read by DOMParser?
NOTE: if I replace txtFile in ... xmldoc = parser.parseFromString("bob","text/xml"), the code works.
Thanks in advance.
I know this is old but I want drop a working example here in case people still come across this
var parser = new DOMParser();
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
var data = parser.parseFromString(evt.target.result, "application/xml");
console.log(data);
};

load an xml file using javascript i

i am trying to upload an xml file using javascript. my javascript code is given below:
var xmlDoc =null;
var abc = new Array();
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument){
xmlDoc=document.implementation.createDocument("","",null);
}
else{
alert('Browser cannot handle this script');
}
if (xmlDoc!=null){
xmlDoc.async=false;
xmlDoc.load("employee.xml");
var x = xmlDoc.getElementsByTagName("EMP");
for (i=0;i<x.length;i++)
{
abc[0] = x[0].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.write("a is "+abc[0]);
abc[1] = x[0].getElementsByTagName("ID1")[0].childNodes[0].nodeValue;
document.write("<br>b is "+abc[1]);
}
}
and my xml file is:
<EMPLOYEE>
<EMP>
<ID>10.99</ID>
<ID1>20.54</ID1>
</EMP>
</EMPLOYEE>
the code is working properly in IE as well as firefox but in Google Chrome, it is not showing anything. can some one tell me where i am wrong or how to correct it.
In order to get the XML file in Chrome you need to execute a GET. For security reasons you cannot load it in a straight forward manner from the file system. Here's code:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlsrc, false);
xmlhttp.send(null);
var xmlDoc = xmlhttp.responseXML.documentElement;

Categories