Hi in an attempt to learn XML I have started a mini-project and am following this totorial: https://www.youtube.com/watch?v=ppzYGd0wi_c. However, the structure of my XML is a bit different to that of this video e.g. I have ids allocated to each section. I have pasted what my XML looks like below:
<?xml version="1.0" encoding=UTF=8?>
<peopleNetwork>
<person id="1">
<name>Alice</name>
<friend>Ruby</friend>
<image>images/ruby.jpg</image>
</person>
<person id="2">
<name>Tom</name>
<friend>Katty</friend>
<image>images/ketty.jpg</image>
</person>
</peopleNetwork>
Since I have id and the person in the video does not in his XML, would I need to process my data differently or would following the same structure work? Can someone point me to some resource / guide me how I can read and process a XML file that has data like above using JavaScript and HTML.
I have written the following code that prompts the user to select a file:
var input = $(document.createElement('input'));
input.attr("type", "file");
input.trigger('click');
return false;
But I am guessing there is more to it, for example saving the read data and processing it somehow. Whilst I have some experience in JavaScript but I have never came across reading and processing data files - therefore I am finding a really difficult - so any guidance on this would be nice.
I understand I will need to use Ajax as the person in the video is doing - one of my question is. In my data I have id however in the video the person doesn't, so I am not sure how to go about handling this.
I am a newbie in XML, but having watched the video I am guessing its something simple but I have no clue where to start. Any help would be appreciated.
Well you can still use input type='file' that allows you to select a file from the user's computer.Then we use FileReader.
html
<div>Xml File: <input type="file" id="fileInput" accept="text/xml" ></div>
<p id="MyXMLText"></p>
script: I'm using jquery and javascript here. This can also be achieved with pure js. We attach onchange event to the input and then use FileReader to open and read the xml as text.
$(function () {
$("#fileInput").on('change', function (e) {
var file = $("#fileInput")[0].files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (e) {
var fileContent = reader.result;
//Sorry cannot give you correct answer why xml parsing fails, but this has to be done here.
fileContent = fileContent.replace('<?xml version="1.0" encoding=UTF=8?>', '').replace(/(?:\r\n|\r|\n)/g, '');
var xmlDoc = $.parseXML(fileContent); //xml document is ready here
//Get all the details for person with id = 1
$("#MyXMLText").append($(xmlDoc).find('person[id="1"]').text() + '<br/>')
//Get the friend's details only for person with id = 1
$("#MyXMLText").append($(xmlDoc).find('person[id="1"]>friend').text() + '<br/>')
//Get the name details only for person with id = 2
$("#MyXMLText").append($(xmlDoc).find('person[id="2"]>name').text() + '<br/>')
}
});
});
parseXML
Let us know.
Related
Maybe naive question but I'm wondering this:
I have an html input allowing me to find a local file on my computer. <input type="file" id="importFile">
From this input, i create a FileReader in js to display the text file content on my page
var search_file = document.getElementById("search_file")
search_file.addEventListener('change', function(){
var reader = new FileReader();
var tmp = [];
reader.readAsText(file_to_survey);
reader.onload = function(e) {
var contents = e.target.result;
//function to edit html thanks to content//
}, false);
This part is actually working well BUT if I edit or replace the file I targeted (with exact same file name), I'm not able to display the file without to search it again with the html input mentionned above.
Is there a way to keep trace of my file even after edition?
Many thanks for your help. I dug quiet a lot to solve my problem but maybe I'm thinking the wrong way. Any clue would be nice.
Because that's how the input type=file element works, and to my best knowledge there is no way for you to force the browser to automatically re-read a file from the user's hard drive without their express consent.
You can put the change handler of the file input in a separate function, and call that function when needed.
function loadFile () {
var reader = new FileReader();
reader.addEventListener('load', function () {
file = reader.result;
// Handle the changes here
console.log(file);
});
reader.readAsText(fileField.files[0]);
}
const fileField = document.getElementById('load'),
reloadBut = document.getElementById('reload');
let file;
reloadBut.addEventListener('click', loadFile);
fileField.addEventListener('change', loadFile);
<input type="file" id="load">
<button id="reload">Load</button>
A separate button is used to reload the file in this snippet, but you can call loadFile where ever you need, ex. in an interval or from some event handler knowing the file was changed etc.
Note: This works in Chrome only, other browsers seem to lose the reference to the file browsed into file input when the file is changed. Also, the file must be properly closed after saving, before reloading.
Is this even a possibility? Never attempted or tried anything like this before, I have no idea where to start.
I have a local file that when a manual button is pressed, it updates an xml file changing
<status>live<\status>
to
<status>killed<\status>
I also have a HTML page that has Iframes pulling live camera feeds for IP cameras. I want to hide the iframe and show a graphic instead when the status is ‘killed’.
Does anyone know if this is possible and where I’d start? Somehow check the xml file regularly or somehow know it has been updated.
Then somehow apply classes or introduce elements such as a div to mask the iframe.
Yes, you can work with XML in JavaScript almost the same as if you were working with HTML. However, without a server-side component, writing the xml document back to the file system will not be possible. You can always download it for the user, but you can't write directly to the file system.
Here's a simple example of updating an XML document with JS. I put both the string of xml and the logic to parse string into an xml doc in the example since I'm not sure what your setup is.
const xmlString = `
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
`;
const xmlDoc = new DOMParser().parseFromString(xmlString, 'text/xml');
document.getElementById('btn').addEventListener('click', e => {
const to = xmlDoc.querySelector('note to');
to.innerHTML = 'Someone New';
console.log('The TO field is now ', xmlDoc.querySelector('note to').innerHTML);
// Set HTML Element from XML
const h1 = document.getElementById('fromXml');
h1.innerText = xmlDoc.querySelector('note heading').innerHTML;
});
<button id="btn">Set To</button>
<h1 id="fromXml"></h1>
I am a novice programmer, and need some help figuring out how to upload a local text file to a textarea inside a website I'm building. I am very fluent in HTML/CSS, I have a decent knowledge of Javascript/JQuery, and I am just learning PHP. Any help you can give I would greatly appreciate. I have an input with type="file" and name="file" and I have a textarea with a class of ".textbox", and I have a button that runs the function "Upload()" Here is the javascript for my site.
var localfile = $("input[name=textfile]").val();
function Upload(){
$(".textbox").append(file);
}
Thanks in advance!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote a few days ago to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
This code shows the basics of reading the file, the file itself is dragged into the text area, a nicer interface, I think, than having to go through the select file mechanisms, but those work equally well to select the file to read.
This is my answer to the similar question : Get text file content using javascript
I think it will be good to
upload the file using iframe which gives you a ajax like user experience is what Gmail doing,
and then read the contents of the file using php
then send the contents back through ajax then append to textarea using js.
Does this makes sense?
I'm wondering if there's any possible way of parsing a binary file in client-side Javascript. I would like to write a page that contains an HTML input form for a binary file ( a sound file is the end game ) and a button that activates a Javascript function that 'parses' the file. Is this possible with client-side Javascript?
I know I can do this with C on the server, but I'd like to avoid anything server-side involved. This is because I'm expecting the task to be computationally intensive and I would like to keep the load and the server low.
From what I've seen on Google, it's possible to parse binary data in Javascript. I'm just not sure how to get the file in the hands of a Javascript function without first passing it to the server.
You can use the FileReader API to read a file client-side
Example:
HTML Markup:
<input id="myfile" type="file"/>
JavaScript:
var fileInput = document.getElementById('myfile');
var fReader = new FileReader();
fReader.onload = function(e) {
console.log(e.target.result); /// <-- this contains an ArrayBuffer
}
fileInput.onchange = function(e) {
var file = this.files[0];
fReader.readAsArrayBuffer(file);
}
JSFiddle: http://jsfiddle.net/wbwHU/ (look at the console for ArrayBuffer output)
I'm currently working on a small project in which I want to convert couple (or more) Markdown files into HTML and then append them to the main document. I want all this to take place client-side. I have chose couple of plugins such as Showdown (Markdown to HTML converter), jQuery (overall DOM manipulation), and Underscore (for simple templating if necessary). I'm stuck where I can't seem to convert a file into HTML (into a string which has HTML in it).
Converting Markdown into HTML is simple enough:
var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');
I'm not sure how to fetch (download) a file into the code (string?).
How do I fetch a file from a URL (that URL is a Markdown file), pass it through Showdown and then get a HTML string? I'm only using JavaScript by the way.
You can get an external file and parse it to a string with ajax. The jQuery way is cleaner, but a vanilla JS version might look something like this:
var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
// Makes sure the document exists and is ready to parse.
if (mdFile.readyState === 4 && mdFile.status === 200)
{
var mdText = mdFile.responseText;
var converter = new showdown.Converter();
converter.makeHtml(mdText);
//Do whatever you want to do with the HTML text
}
}
jQuery Method:
$.ajax({
url: "info.md",
context: document.body,
success: function(mdText){
//where text will be the text returned by the ajax call
var converter = new showdown.Converter();
var htmlText = converter.makeHtml(mdText);
$(".outputDiv").append(htmlText); //append this to a div with class outputDiv
}
});
Note: This assumes the files you want to parse are on your own server. If the files are on the client (IE user files) you'll need to take a different approach
Update
The above methods will work if the files you want are on the same server as you. If they are NOT then you will have to look into CORS if you control the remote server, and a server side solution if you do not. This question provides some relevant background on cross-domain requests.
Once you have the HTML string, you can append to the whatever DOM element you wish, by simply calling:
var myElement = document.getElementById('myElement');
myElement.innerHTML += markdownHTML;
...where markdownHTML is the html gotten back from makeHTML.