ajaxslt unable to get node using XPATH - javascript

I am using the ajaxslt javascript library.(http://code.google.com/p/ajaxslt/) I am trying to get the node using XPATH
My XML is as follows:
<page>
<message>
Hello World.
</message>
</page>
I am trying to use //page so that I can all nodes below page i.e. message node. When i try to print the same. I am getting only Hello World as output.
Following is the code snippet i used.
<script src="./js/xpath.js" language="JavaScript"></script>
<script src="./js/xpath_script.js" language="JavaScript"></script>
<script type="text/javascript">
function showMessage(){
var xml = document.getElementById('xml');
var ctx = new ExprContext(xmlParse(xml.value));
var expr = xpathParse("//page");
var result = expr.evaluate(ctx);
alert("res:"+result.stringValue());
}
Can anybody tell me what i am doing wrong here?
Thanks in advance.
Saravanan K

You must use:
//page/message
this selects in general more than one message element. You need to iterate through the returned node-list and produce the string value of each selected message element.

Related

How to strip the <html> Tag from string?

I have the following response from an HTTP get.
<HTML><BODY>Now='11/7/2017 4:08:34 PM' Process='chrome' SessionID=1 User='Local\User' Culture='en-US'<BR></BODY></HTML>
I need to get the data there in the body into a JSON object. So I tried to remove HTML tags. Though it is different, I have tried, as there in this solution. It works for HTML tags but not for <html> itself.
I have tried also as below:
var content = "<HTML><BODY>Now='11/7/2017 4:08:34 PM' Process='chrome' SessionID=1 User='Local\User' Culture='en-US'<BR></BODY></HTML>";
var tag = document.createElement("html");
tag.outerHtml = content;
It gives the following error:
Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element': This element has no parent node.
Though I know that it can be achieved with regex, I want to do it without regex.
Could someone resolve it?
Use DOMParser() to convert the string of HTML into a DOM:
var html = `<HTML><BODY>Now='11/7/2017 4:08:34 PM' Process='chrome' SessionID=1 User='Local\User' Culture='en-US'<BR></BODY></HTML>`;
var parser = new DOMParser();
var html_dom = parser.parseFromString(html, "text/html");
var body = html_dom.querySelector("body");
var content = body.innerHTML;
console.log(content);
Just created a simple codepen. Please try, it shall work:
https://codepen.io/vishalkaului/pen/rYMGoy
+6 and - 16 are to exclude the content before the starting<BODY> tag and after the closing </BODY> tag. It includes both the exclusion for the <BODY></BODY> tags.
(function () {
let serverResponse = "<HTML><BODY>Now='11/7/2017 4:08:34 PM'
Process='chrome' SessionID=1 User='Local\User' Culture='en-
US'<BR></BODY></HTML>";
console.log(serverResponse.substr(serverResponse.indexOf('<BODY>')+6,serverResponse.indexOf('</BODY>')-16));
})()
Note:
This solution caters only when you know that the structure of the response is same. Though, content can vary but the tags are same before and after the response data.

Use result of vkbeautify pretty print in TextArea

Hi I have the following TextArea to display a JSON string:
<TextArea id="payloadlabel" width="1000px" height='auto' rows='80' />.
My problem is that the JSON string is not well formatted, see example.
I'm using the library vkbeautify as follows:
var myObj = {
"urn.getxxxx": {
"urn.xxxx" : "cxxxxx-44e9-xxxx-a91b-0000xxxx\\xxxxx\\3xx\\xx\\x\\",
"urn.xxxx" : "xxxxx",
"urn.xxxxx" : "x",
"urn.xxxx": "20xx-07-08xxx:03:41+02:00"
}
};
var request = JSON.stringify(myObj);
vkbeautify.json(request);
var tryModel = new sap.ui.model.json.JSONModel();
tryModel.setData(request);
var payloadtxta = sap.ui.getCore().byId(view.createId('payloadlabel'));
payloadtxta.setModel(tryModel);
payloadtxta.setValue(request);
Unfortunately it's not working. The JSON content remains exactly like in the example. What is wrong here?
I have the vkbeautify.js file in my web content and I included it in the index.
<script type="text/javascript" src="vkbeautify.js"></script>
As I get no error for the vkbeautify method I think I included it in the right way. Suggestions are welcomed if you know any other method to format JSON content any other library or idea. Thank you.
You are using the wrong variable (BTW: JSON.stringify is superfluous as you already have a JSON string):
var beautifiedObj = vkbeautify.json(myObj);
var payloadtxta = this.byId(view.createId("payloadlabel"));
payloadtxta.setValue(beautifiedObj);
The model is never used in your example, thus you can remove it or use it as intendend by UI5 and bind the control directly to the model property.
<TextArea id="payloadlabel" value={/request}" width="1000px" height='auto' rows='80' />.
this.setModel(new sap.ui.model.json.JSONModel({
"request" : vkbeautify.json(myObj)
});
Looking at the source of vkbeautify, it is slightly pointless if you are just using that library for this purpose - you can do what you need with standard JavaScript:
var beautifiedTxt = JSON.stringify(myObj, null, 4);
var payloadtxta = sap.ui.getCore().byId(view.createId("payloadlabel"));
payloadtxta.setValue(beautifiedTxt);
Check out the documentation of JSON.stringify on MDN here - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
REF source for vkbeautify - https://github.com/vkiryukhin/vkBeautify/blob/master/vkbeautify.js#L152.

Trouble getting json back

I'm using the current json structure of this:
jsonp = {"game":[
{"id":"1","gameImage":"qqq.jpg"}
],
"game":[
{"id":"2","gameImage":"hhh.jpg"}
]
}
I'm trying to just get back all the gameImage values. I tried the following but it just won't work. Any ideas?
<html>
<head></head>
<body>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="gameData.json"></script>
<script>
$(document).ready(function() {
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
alert(this['gameImage']);
});
});
</script>
</body>
</html>
Assuming the first code you show is in the file (incorrectly) named "gameData.json", what you're trying to parse isn't JSON (or JSONP), it's plain JavaScript.
So don't parse it.
Change
var obj = $.parseJSON(jsonp);
to
var obj = jsonp;
Notes :
JSON is a text based data interchange format. Your confusion might come from the many young developers using non-sensical expressions like "JSON object"...
You should avoid naming jsonp a variable holding a plain JavaScript object.
If you prefer to load a JSON file instead of executing a JavaScript file, then
remove the "jsonp = part to make it a real JSON file
remove the script element (as it's not JavaScript anymore)
load the JSON file using ajax
Here's how the JavaScript would be like :
$(document).ready(function() {
$.getJSON("gameData.json", function(obj){
$.each(obj, function() {
alert(this['gameImage']);
});
});
});
or, if you can afford not supporting IE8 :
$(document).ready(function() {
$.getJSON("gameData.json", function(arr){
arr.forEach(function(item){
console.log(item.gameImage); // yes, prefer the console over alert
});
});
});

What is the best way to parse html in google apps script

var page = UrlFetchApp.fetch(contestURL);
var doc = XmlService.parse(page);
The above code gives a parse error when used, however if I replace the XmlService class with the deprecated Xml class, with the lenient flag set, it parses the html properly.
var page = UrlFetchApp.fetch(contestURL);
var doc = Xml.parse(page, true);
The problem is mostly caused because of no CDATA in the javascript part of the html and the parser complains with the following error.
The entity name must immediately follow the '&' in the entity reference.
Even if I remove all the <script>(.*?)</script> using regex, it still complains because the <br> tags aren't closed.
Is there a clean way of parsing html into a DOM tree.
I ran into this exact same problem. I was able to circumvent it by first using the deprecated Xml.parse, since it still works, then selecting the body XmlElement, then passing in its Xml String into the new XmlService.parse method:
var page = UrlFetchApp.fetch(contestURL);
var doc = Xml.parse(page, true);
var bodyHtml = doc.html.body.toXmlString();
doc = XmlService.parse(bodyHtml);
var root = doc.getRootElement();
Note: This solution may not work if the old Xml.parse is completely removed from Google Scripts.
In 2021, the best way to parse HTML on the .gs side that I know of is...
Click + next to Library
Enter 1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0
Click "Look up"
Click Add
Sample usage:
const contentText = UrlFetchApp.fetch('https://www.somesite.com/').getContentText();
const $ = Cheerio.load(contentText);
$('.some-class').first().text();
That's it -- this is probably the closest we'll get to doing jQuery-like DOM selection in GAS. The .first() is important or else you may extract more content than you expected (think of it as using querySelector() instead of querySelectorAll()).
Credit where credit is due: https://github.com/tani/cheeriogs
As of May 2020, you can now use the Cheerio library for Google Apps Script to do this.
Returns the content of Wikipedia's Main Page
const content = getContent_('https://en.wikipedia.org');
const $ = Cheerio.load(content);
Logger.log($('#mp-right').text());
Returns the content of the first paragraph <p> of Wikipedia's Main Page
const content = getContent_('https://en.wikipedia.org');
const $ = Cheerio.load(content);
Logger.log($('p').first().text());
To add to your project:
Select Resources - Libraries... in the Google Apps Script editor. Enter the project key 1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0 in the Add a library field, and click "Add". Select the highest version number, and click "Save".
I found that the best way to parse html in google apps is to avoid using XmlService.parse or Xml.parse. XmlService.parse doesn't work well with bad html code from certain websites.
Here a basic example on how you can parse any website easily without using XmlService.parse or Xml.parse. In this example, i am retrieving a list of president from "wikipedia.org/wiki/President_of_the_United_States"
whit a regular javascript document.getElementsByTagName(), and pasting the values into my google spreadsheet.
1- Create a new Google Sheet;
2- Click the menu Tools > Script editor... to open a new tab with the code editor window and copy the following code into your Code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Parse Menu")
.addItem("Parse", "parserMenuItem")
.addToUi();
}
function parserMenuItem() {
var sideBar = HtmlService.createHtmlOutputFromFile("test");
SpreadsheetApp.getUi().showSidebar(sideBar);
}
function getUrlData(url) {
var doc = UrlFetchApp.fetch(url).getContentText()
return doc
}
function writeToSpreadSheet(data) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var row=1
for (var i = 0; i < data.length; i++) {
var x = data[i];
var range = sheet.getRange(row, 1)
range.setValue(x);
var row = row+1
}
}
3- Add an HTML file to your Apps Script project. Open the Script Editor and choose File > New > Html File, and name it 'test'.Then copy the following code into your test.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id= "mButon" type="button" value="Click here to get list"
onclick="parse()">
<div hidden id="mOutput"></div>
</body>
<script>
window.onload = onOpen;
function onOpen() {
var url = "https://en.wikipedia.org/wiki/President_of_the_United_States"
google.script.run.withSuccessHandler(writeHtmlOutput).getUrlData(url)
document.getElementById("mButon").style.visibility = "visible";
}
function writeHtmlOutput(x) {
document.getElementById('mOutput').innerHTML = x;
}
function parse() {
var list = document.getElementsByTagName("area");
var data = [];
for (var i = 0; i < list.length; i++) {
var x = list[i];
data.push(x.getAttribute("title"))
}
google.script.run.writeToSpreadSheet(data);
}
</script>
</html>
4- Save your gs and html files and Go back to your spreadsheet. Reload your Spreadsheet. Click on "Parse Menu" - "Parse". Then click on "Click here to get list" in the sidebar.
Xml.parse() has an option to turn on lenient parsing, which helps when parsing HTML. Note that the Xml service is deprecated however, and the newer XmlService doesn't have this functionality.
For simple tasks such as grabbing one value from a webpage, you could use a regular expression. Regex is notoriously bad for parsing HTML as there's all sorts of weird cases it can get tripped up, but if you're confident about the HTML you're accessing this can sometimes be the simplest way.
Here's an example that fetches the contents of the page's <title> tag:
var page = UrlFetchApp.fetch(contestURL);
var regExp = new RegExp("<title>(.*)</title>", "gi");
var result = regExp.exec(page.getContentText());
// [1] is the match group when using parenthesis in the pattern
var value = result ? result[1] : 'No title found';
I know it is not exactly what OP asked, but I found this question when I was looking for some html parsing options - so it might be useful for others as well.
There is an easy to use the library for TEXT parsing. It's useful if you want to get only one piece of information from the html(xml) code.
EDIT 2021: The script library id is:
1Mc8BthYthXx6CoIz90-JiSzSafVnT6U3t0z_W3hLTAX5ek4w0G_EIrNw
It works like in the picture above
function getData() {
var url = "https://chrome.google.com/webstore/detail/signaturesatori-central-s/fejomcfhljndadjlojamaklegghjnjfn?hl=en";
var fromText = '<span class="e-f-ih" title="';
var toText = '">';
var content = UrlFetchApp.fetch(url).getContentText();
var scraped = Parser
.data(content)
.from(fromText)
.to(toText)
.build();
Logger.log(scraped);
return scraped;
}
If you are using
Cheerio library for Google Apps Script
Source code
Library page (⭐ star it!)
Installation by library ID:
1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0
A function to get current emojis from unicode.org:
function getEmojis() {
var t = new Date();
var url = 'https://unicode.org/emoji/charts/full-emoji-list.html';
var fetch = UrlFetchApp.fetch(url);
var contentText = fetch.getContentText();
//console.log(new Date() - t);
// Cherio
var $ = Cheerio.load(contentText);
var data = [];
$("table > tbody > tr").each((index, element) => {
var row = [];
$(element).find("td").each((index, child) => {
row.push($(child).text());
});
if (row.length > 0) {
data.push(row);
}
});
//console.log(data);
//console.log(new Date() - t);
// Result
return data;
}
↑ Sample code shows how to parse table and put it into [[array]]
May be used as a custom function:
Bonus
Parsing the site may be a time-consuming operation + you may reach the limit.
Here's a test file with a full version of the script:
https://docs.google.com/spreadsheets/d/1iO7YjYWyfseQu_YCfRbGDPg7NskOgMu_iO1iGjr7KxY/edit#gid=93365395
↑ it uses CasheService to reduce the number of calls.
Natively there's no way unless you do what you already tried which wont work if the html doesnt conform with the xml format.
There are two options
a) One is to use JavaScript's string functions. First locate your tag using string.indexOf() and then extract the data you want using string.substring().
b) The other option is to make use of the Xml Service.
It's not possible to create an HTML DOM server-side in Apps Script. Using regular expressions is likely your best option, at least for simple parsing.

javascript get Value

code :
<script type="text/javascript" src="http://127.0.0.1/Test.js#username=stackoverflow">
</script>
iwant to know ,how to get the username in Test.js
file
Test.js :
var username = ??
///////////// #username=stackoverflow
thanks advance
If you are trying to do all this on the client side, it's much better to use:
<script type="text/javascript">//<![CDATA[
var username = "stackoverflow";
//]]></script>
<script type="text/javascript" src="http://127.0.0.1/Test.js"></script>
That way, you don't need to tackle the issue of reading the src attribute of the script tag somehow.
The query portion of the URL is invalid. It should be:
http://127.0.0.1/Test.js?username=stackoverflow
The # is treated as a named anchor.
The gup function isn't good because the parameter is on the script tag, not the HTML output page.
The location object (location.href, location.search...) refers to the HTML page where the script included.
There are 2 other options:
Use this
Use #idealmachine answer. You can wrap the global variable with simple object in order to avoid conflict with other global JS variables

Categories