Skip to content

Instantly share code, notes, and snippets.

@vs4vijay
Created September 27, 2013 06:35
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save vs4vijay/6724868 to your computer and use it in GitHub Desktop.
Save vs4vijay/6724868 to your computer and use it in GitHub Desktop.
Extract Data from XPath via Google Apps Script
function getDataFromXpath(path, url) {
var data = UrlFetchApp.fetch(url);
var text = data.getContentText();
var xmlDoc = Xml.parse(text, true);
// Replacing tbody tag because app script doesnt understand.
path = path.replace("/html/","").replace("/tbody","","g");
var tags = path.split("/");
Logger.log("tags : " + tags);
// getting the DOM of HTML
var element = xmlDoc.getElement();
for(var i in tags) {
var tag = tags[i];
Logger.log("Tag : " + tag);
var index = tag.indexOf("[");
if(index != -1) {
var val = parseInt(tag[index+1]);
tag = tag.substring(0,index);
element = element.getElements(tag)[val-1];
} else {
element = element.getElement(tag);
}
//Logger.log(element.toXmlString());
}
return element.getText() ;//+ ' [ ' + element.getAttribute("href").getValue() + ' ] ';
}
@ntsd
Copy link

ntsd commented Jan 18, 2022

@mananchawla8 I think XML has changed to XmlService . but the script doesn't work btw.
https://developers.google.com/apps-script/reference/xml-service

@konnovdev
Copy link

yea this code snippet does not work any more. Which is not surprising giving that it was published 9 years ago

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment