How to use the select function from xpath
Find comprehensive JavaScript xpath.select code examples handpicked from public code repositorys.
xpath.select is a function in the xpath library that selects nodes from an XML document using XPath expressions.
GitHub: apigee/apigeelint
74 75 76 77 78 79 80 81 82 83 84 85
.replace(/^Object.<anonymous>\s*\(/gm, "{anonymous}()@") .split("\n"); } function selectAttributeValue(item, path) { var attr = xpath.select(path, item); return (attr[0] && attr[0].value) || ""; } function selectTagValue(item, path) {
+ 105 other calls in file
74 75 76 77 78 79 80 81 82
const requestBase64 = descriptor.formBody.SAMLRequest; const requestXML = new Buffer(requestBase64, "base64").toString("utf8"); const request = new xmldom.DOMParser().parseFromString(requestXML); xpath.select("//*[local-name(.)='AuthnRequest']", request).length.should.equal(1); xpath.select("//*[local-name(.)='Signature']", request).length.should.equal(1); const sigNode = xpath.select("//*[local-name(.)='Signature']", request)[0]; signing.validateXMLSignature(requestXML, sigNode, sp.sp.credentials[0]).should.equal(0); }); });
How does xpath.select work?
xpath.select is a function in the xpath library that selects nodes from an XML document using XPath expressions. When you call xpath.select, you provide an XPath expression and an XML document. The function then evaluates the XPath expression against the XML document and returns a list of matching nodes. Here's an implementation of xpath.select to illustrate how it works: javascript Copy code {{{{{{{ const xpath = require('xpath'); const dom = require('xmldom').DOMParser; xpath.select = (expression, document) => { const xml = new dom().parseFromString(document); const nodes = xml.evaluate(expression, xml, null, xpath.XPathResult.ANY_TYPE, null); const result = []; let node = nodes.iterateNext(); while (node) { result.push(node); node = nodes.iterateNext(); } return result; }; In this implementation, we extend the xpath library by adding a new method called select using xpath.select = (expression, document) => {...}. The select method takes an XPath expression as its first argument and an XML document as its second argument. We then create a new DOMParser object using const xml = new dom().parseFromString(document). The DOMParser object parses the XML document and creates a new XML DOM object. We then evaluate the XPath expression against the XML DOM object using xml.evaluate(expression, xml, null, xpath.XPathResult.ANY_TYPE, null). The evaluate method returns an XPathResult object that contains a list of matching nodes. We then create a new empty array called result and use a while loop to iterate through each node in the XPathResult object. We call nodes.iterateNext() to get the next node and push it into the result array using result.push(node). Finally, we return the result array, which contains a list of matching nodes. Overall, xpath.select is a useful function in the xpath library that allows you to select nodes from an XML document using XPath expressions.
GitHub: MooNight16/qinglong-js
4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711
return res; } function ParseHtml(html) { let doc = domParser.parseFromString(html); let nodes = xpath.select('//script', doc); let node = nodes[4].childNodes[0]; let babelStr; let tdom = new JSDOM(`<script>${DealScriptStr(node.data)}</script>`, { runScripts: 'dangerously'
+ 243 other calls in file
64 65 66 67 68 69 70 71 72
if (!table) { console.error('No table found in the HTML response...') process.exit(1) } const rows = xpath.select('tr', table) console.log('Found rows in functions table:', rows.length) const newFunctions = []
+ 21 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
const xpath = require("xpath"); const dom = require("xmldom").DOMParser; const xml = ` Everyday Italian Giada De Laurentiis 2005 30.00 Harry Potter J.K. Rowling 2005 29.99 `; const xmlDoc = new dom().parseFromString(xml); const nodes = xpath.select("//book/title", xmlDoc); console.log(nodes); // Output: [ Everyday Italian, Harry Potter ]
In this example, we first require the xpath library using const xpath = require('xpath'). We also require the xmldom library using const dom = require('xmldom').DOMParser. We then define an XML document as a string called xml that contains some books with titles, authors, years, and prices. We create a new DOMParser object using new dom().parseFromString(xml). The DOMParser object parses the XML document and creates a new XML DOM object called xmlDoc. We then call xpath.select('//book/title', xmlDoc) to select all title elements that are children of book elements. The XPath expression '//book/title' selects all title elements anywhere in the document that are descendants of book elements. xpath.select returns an array of matching nodes, which in this case are two title elements. We then log the nodes variable to the console, which outputs an array of title elements: javascript Copy code
GitHub: gitadvisor/gitscan-action
2 3 4 5 6 7 8 9 10 11 12
const app = express(); app.get('/some/route', function(req, res) { let tainted = req.param("userName"); xpath.parse(tainted); // NOT OK xpath.select(tainted); // NOT OK xpath.select1(tainted); // NOT OK let expr = xpath.useNamespaces(map); expr(tainted); // NOT OK });
844 845 846 847 848 849 850 851 852 853
const result = '`'+inbody+'`'; ;(async function () { try { const result = await transform(inbody, template2); var data = result; var nodes = xpath.select('//EDIHeader/EDICareandContent/Fibre/FibreComponents', root); var counter = 1; var fibres = {}; nodes.forEach(function(item, i) { var fibrecomponents = '';
+ 7 other calls in file
GitHub: kapturebox/server
51 52 53 54 55 56 57 58 59
}, function (err, resp, body) { if (err) return reject(err); try { var doc = new dom({ errorHandler: function (o) { } }).parseFromString(body); var shownames_xml = xpath.select(SHOWS_XPATH, doc); } catch (err) { return reject(new Error(`cant parse showrss xml: ${err}`)); }
GitHub: ruy1su/Aztec-Website
75 76 77 78 79 80 81 82 83 84
return; var nodes = xpath.select("//body//p", doc); var abstractNodes = xpath.select("//abstract//p", doc); if (typeof(abstractNodes[0]) == "undefined"){ if (idx == files.length - 1) {
+ 2 other calls in file
271 272 273 274 275 276 277 278 279 280
errorLog[errorLevel.toString()].push(msg); } let nodes = []; try { nodes = xpath.select(myXPath, doc); if(nodes && nodes.length > 0){ var out = [];
+ 63 other calls in file
286 287 288 289 290 291 292 293 294 295 296 297
function get_csproj_package_version(doc) { const xpath_selector = args.xpath.replace("\$1", args.package) // console.log(xpath_selector); const verAttribute = xpath.select(xpath_selector, doc); // console.log(verAttribute); if (verAttribute === undefined || verAttribute.length == 0 ||
+ 24 other calls in file
GitHub: jlassiwissal/Api-ETL
15 16 17 18 19 20 21 22 23 24
var contents = fs.readFileSync(opts.file, { encoding: encoding }); var doc = new Dom().parseFromString(contents); var queryText = function(str) { var context = this; var result = Xpath.select(str + '/text()', context, true); if (result) { return result.toString(); } else { return null;
+ 251 other calls in file
136 137 138 139 140 141 142 143 144
typeName, itemSelector, itemProps, }) => { // try and select all items in the document by the given selector const items = xpath.select(itemSelector, document.documentElement); // apply the property mapping to each item return items.map((item, index) => {
+ 70 other calls in file
62 63 64 65 66 67 68 69 70 71
Method: Method, Found: Found, Conclusion: Conclusion }; } else { var vItems = xpath.select("/Audit/PlugIns/PlugIn[@id='" + PluginId + "']/Domain[@nr='" + DomainId + "']/Area[@nr='" + AreaId + "']/Issue[@nr='" + IssueId + "']/Matrix/Objectives/obj/tx[@l='" + selectedLang + "']/@name",doc); for (var i=0; i<vItems.length; i++) { Objectives= Objectives + vItems[i].nodeValue; } var vItems = xpath.select("/Audit/PlugIns/PlugIn[@id='" + PluginId + "']/Domain[@nr='" + DomainId + "']/Area[@nr='" + AreaId + "']/Issue[@nr='" + IssueId + "']/Matrix/Criteria/cri/tx[@l='" + selectedLang + "']/@name",doc);
+ 563 other calls in file
92 93 94 95 96 97 98 99 100 101
* @param {string} html * @returns {Array<string>} Array of lyric blocks */ function parseLyrics(t) { const doc = new DOMParser({ errorHandler: {warning:()=>{}, error:()=>{}} }).parseFromString(t); const nodes = select('//span[@class="lyrics__content__ok"]', doc); data = { title: select('//h1', doc)[0].lastChild.data, artist: select('//h2', doc)[0].firstChild.firstChild.firstChild.data, lyrics: ""
+ 215 other calls in file
76 77 78 79 80 81 82 83 84 85
Description: tempDescription, Number: vNumber, Priority: xpath.select("/Audit/Recommendations/Recommendation[@nr='" + vRecommendations[i].nodeValue + "']/@priority",doc)[0].nodeValue, Risk: xpath.select("/Audit/Recommendations/Recommendation[@nr='" + vRecommendations[i].nodeValue + "']/@risk",doc)[0].nodeValue, Riskevaluation: xpath.select("/Audit/Recommendations/Recommendation[@nr='" + vRecommendations[i].nodeValue + "']/@riskevaluation",doc)[0].nodeValue, Repeated: xpath.select("/Audit/Recommendations/Recommendation[@nr='" + vRecommendations[i].nodeValue + "']/@repeated",doc)[0].nodeValue, Timeline: tempTimeline, Status: tempStatus, Findings: tempFindings };
+ 29 other calls in file
176 177 178 179 180 181 182 183 184 185
if (page.status === 200) { const xpathString = 'string(/html/body/div[2]/section/ol/li[1]/text())'; var doc = new dom().parseFromString(page.data) var currentSong = xpath.select(xpathString, doc) console.log('Printing current song', currentSong); message = currentSong; }
GitHub: gamus-space/scraper
29 30 31 32 33 34 35 36 37
const gameInfo = xpath.select1("./following::h2[normalize-space(text()) = 'Game info']/following-sibling::p", page); const game = options.game || xpath.select1("normalize-space(./big[normalize-space(text()) = 'Name:']/following-sibling::a/text())", gameInfo); const developersStart = xpath.select1("./big[normalize-space(text()) = 'Developers:' or normalize-space(text()) = 'Developer:']", gameInfo); const developersEnd = xpath.select1("./following-sibling::big", developersStart); const developers = takeUntil(xpath.select("./following-sibling::*[name() = 'a' or name() = 'big']", developersStart), developersEnd).map(dev => xpath.select("normalize-space(./text())", dev)); const publishersStart = xpath.select1("./big[normalize-space(text()) = 'Publishers:' or normalize-space(text()) = 'Publisher:']", gameInfo); const publishersEnd = xpath.select1("./following-sibling::big", publishersStart); const publishers = takeUntil(xpath.select("./following-sibling::*[name() = 'a' or name() = 'big']", publishersStart), publishersEnd).map(dev => xpath.select("normalize-space(./text())", dev));
+ 5 other calls in file
GitHub: gamus-space/scraper
19 20 21 22 23 24 25 26 27 28
const platform = PLATFORM_MAP[platformStr] || platformStr; const year = parseInt(xpath.select('normalize-space(./tr[normalize-space(./td[1]) = "Year:"]/td[2])', metricsTable)) || null; const developers = [xpath.select('normalize-space(./tr[normalize-space(./td[1]) = "Developer:"]/td[2])', metricsTable)]; const releasesTitle = xpath.select1('//div[@id="mw-content-text"]//h2[span/@id="Releases"]', doc); const releasesTables = xpath.select('./following-sibling::*/descendant-or-self::table//table', releasesTitle); const publishers = [...new Set(releasesTables.map(table => xpath.select1('normalize-space(./tr[normalize-space(./td[1]) = "Publisher:"]/td[2])', table)))]; const ripTitle = xpath.select1('//div[@id="mw-content-text"]//h3[span/@id="Game_Rip"]', doc); const mainDownloadLink = xpath.select1('string(./following-sibling::*/descendant-or-self::table[1]//a[normalize-space(text()) = "Download"]/@href)', ripTitle);
+ 5 other calls in file
GitHub: gamus-space/scraper
41 42 43 44 45 46 47 48 49 50
const html = await (await fetch(url)).text(); const doc = new dom().parseFromString(html); const infobox = xpath.select1("//table[contains(@class, 'infobox')]", doc); const title = normalizeName(xpath.select("normalize-space(.//tr[1]/th/i)", infobox)); //const composers = xpath.select(".//tr[normalize-space(th/text()) = 'Composer(s)']/td/a/text()", infobox).map(t => t.data); const developers = xpath.select(".//tr[normalize-space(th/text()) = 'Team(s)']/td/a/text()", infobox).map(t => t.data); const publishers = xpath.select(".//tr[normalize-space(th/text()) = 'Publisher(s)']/td/a/text()", infobox).map(t => t.data); const year = parseInt(xpath.select("normalize-space(.//tr[normalize-space(th/text()) = 'Year published']/td)", infobox)) || null; const music = xpath.select1("//h2/span[normalize-space() = 'UnExoticA Music Files']", doc);
+ 9 other calls in file
19 20 21 22 23 24 25 26 27 28
page = page + 1; const res = syncRequest('GET', pidUrl(page)); const xml = res.getBody('utf8'); const doc = new dom().parseFromString(xml); remainder = xpath.select1('/programmeList/remainder', doc).firstChild.data; const links = xpath.select('//link', doc); const titles = xpath.select('//title', doc); for (let i=0; i < links.length; i++) { const pid = /(\d\d*)/.exec(links[i].firstChild.data)[1]; const title = titles[i].firstChild.data;
xpath.select is the most popular function in xpath (2001 examples)