javascript to search attributes in an XML document - javascript

i want to make a javascript that reads a XML document as an input (let say "C010.xml"), searches for certain tags and then returns the value within these tags.
For example, in the expression
<lesson_mode>normal</lesson_mode>
to return the attribute "normal".
Could you suggest sth please?
Thanks!

You need to get the XML first. Use XMLHttpRequest for that, then parse the response via DOMParser which returns a Document instance. Then you can just access the value like this: doc.getElementsByTagName('lesson_node')[0].textContent
I don't know what experience you have, so this is the basic structure:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'C010.xml', true);
xhr.onload = function () {
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, 'application/xml');
var value = doc.getElementsByTagName('lesson_node')[0].textContent;
};
xhr.send(null);
Note that this is not by any means cross-browser nowadays. You would have to search for a slightly different way to parse the response in IE.

Related

How to get only a part of a file with a Javascript AJAX request(no jQuery)

I have checked Google and answers and tutorials, I know how to get only a part of a file by AJAX using jQuery, but I could not find any instructions on how to do it with plain JS.
I have tried:
xhr.open('GET', 'https://website.html .my-class');
Does not work, lookign for an element by ID did not work either.
xhr.open('GET', 'https://website.html');
This returns the whole file.
I have not tried to cache and fragment the whole returned file, I doubt that would work anyway.
So, how is this done? Certainly it's possible, right?
You can use DOMParser() to create an HTML document from XMLHttpRequest.responseText, then use document.querySelector() or document.querySelectorAll() to retrieve the specific selectors from document
var file = `data:text/html,
<!DOCTYPE html>
<html>
<body>
<div class="my-class">my class</div>
</body>
</html>`;
var request = new XMLHttpRequest();
request.open("GET", file, true);
request.onload = function() {
var html = request.responseText;
var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");
var el = doc.querySelector(".my-class");
document.body.appendChild(el);
}
request.send();
I recommend you use jquery. Less time.
Alternatively you can use the DOMParser object of web API.
https://developer.mozilla.org/it/docs/Web/API/DOMParser
this parse your file text/html, then you can search for the class you want

How to load a PDF into a blob so it can be uploaded?

I'm working on a testing framework that needs to pass files to the drop listener of a PLUpload instance. I need to create blob objects to pass inside a Data Transfer Object of the sort generated on a Drag / Drop event. I have it working fine for text files and image files. I would like to add support for PDF's, but it seems that I can't get the encoding right after retrieving the response. The response is coming back as text because I'm using Sahi to retrieve it in order to avoid Cross-Domain issues.
In short: the string I'm receiving is UTF-8 encoded and therefore the content looks like you opened a PDF with a text editor. I am wondering how to convert this back into the necessary format to create a blob, so that after the document gets uploaded everything looks okay.
What steps do I need to go through to convert the UTF-8 string into the proper blob object? (Yes, I am aware I could submit an XHR request and change the responseType property and (maybe) get closer, however due to complications with the way Sahi operates I'm not going to explain here why I would prefer not to go this route).
Also, I'm not familiar enough but I have a hunch maybe I lose data by retrieving it as a string? If that's the case I'll find another approach.
The existing code and the most recent approach I have tried is here:
var data = '%PDF-1.7%����115 0 obj<</Linearized 1/L ...'
var arr = [];
var utf8 = unescape(encodeURIComponent(data));
for (var i = 0; i < utf8.length; i++) {
arr.push(utf8.charCodeAt(i));
}
var file = new Blob(arr, {type: 'application/pdf'});
It looks like you were close. I just did this for a site which needed to read a PDF from another website and drop it into a fileuploader plugin. Here is what worked for me:
var url = "http://some-websites.com/Pdf/";
//You may not need this part if you have the PDF data locally already
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//console.log(this.response, typeof this.response);
//now convert your Blob from the response into a File and give it a name
var fileOfBlob = new File([this.response], 'your_file.pdf');
// Now do something with the File
// for filuploader (blueimp), just use the add method
$('#fileupload').fileupload('add', {
files: [ fileOfBlob ],
fileInput: $(this)
});
}
}
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
I found help on the XHR as blob here. Then this SO answer helped me with naming the File. You might be able to use the Blob by itself, but you won't be able to give it a name unless its passed into a File.

Javascript on Firefox: Accessing binary data from html object possible?

On an html page I have an <object> that hosts a pdf.
I would need to access the binary data of the pdf via Javascript, but I cannot figure out how
to accomplish that. I get access to the object element itself but cannot think of a method for getting the data in it.
Is it possible at all?
You can not get the binary from an object tag, but you can make an AJAX request to the server and get it as ArrayBuffer by using the new responseType attribute:
var http = new XMLHttpRequest();
http.open("get", "somefile.pdf", true);
http.responseType = "arraybuffer";
http.onload = function(e)
{
if(http.response)
{
// http.response contains the file
}
};
http.send(null);
Note that this method only works in newer browsers and is obviously restricted by the Same-Origin-Policy.

Parsing HTML with XPath/XMLHttpRequest

I'm trying to download an HTML page, and parse it using XMLHttpRequest(on the most recent Safari browser). Unfortunately, I can't get it to work!
var url = "http://google.com";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4){
response = xmlhttp.responseText;
var doc = new DOMParser().parseFromString(response, "text/xml");
console.log(doc);
var nodes = document.evaluate("//a/text()",doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
console.log(nodes);
console.log(nodes.snapshotLength);
for(var i =0; i<nodes.snapshotLength; i++){
thisElement = nodes.snapshotItem(i);
console.log(thisElement.nodeName);
}
}
};
xmlhttp.send(null);
The text gets downloaded successfully(response contains the valid HTML), and is parsed into a tree correctly(doc represents a valid DOM for the page). However, nodes.snapshotLength is 0, despite the fact that the query is valid and should have results. Any ideas on what's going wrong?
If you are using either:
a JS library or
you have a modern browser with the querySelectorAll method available (Safari is one)
You can try to use CSS selectors to parse the DOM instead of XPATH.
HTML is not XML. The two are not interchangeable. Unless the "HTML" is actually XHTML, you will not be able to use XPATH to process it.

yahoo widgets and importing rss/xml feed using javascript

I'm playing about creating an RSS reader widget using Konfabulator/Yahoo. At the moment I'm
pulling in the RSS using
var xmlDoc = COM.createObject("Microsoft.XMLDOM");
xmlDoc.loadXML("http:foo.com/feed.rss");
I've simplified it here by removing the error handling, but what else could I use to do the same task using konfabulator? And how cross platform is this?
COM is Windows-specific, and Yahoo Widgets has XML parsing built-in; so stay away from MSXML :P
You should use the built-in XMLDOM object instead. But since you want to download the XML document from the ’net anyway, XMLHttpRequest supports getting a DOMDocument directly, without having to pass the data to XMLDOM:
var request = new XMLHttpRequest();
request.open( "GET", "http://www.example.com/feed.rss", false);
request.send();
var xmlDoc = request.responseXML;
It works exactly like the XMLHttpRequest on a browser.
For completeness, if you need to parse XML from a string:
var xmlDoc = XMLDOM.parse("<foo>hello world</foo>");

Categories

Resources