### Install Development Assets Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Commands to install necessary test assets for the FontoXPath development environment on UNIX and Windows systems. ```sh ./test/install-assets.sh ``` ```powershell ./test/install-assets.ps1 ``` -------------------------------- ### Profile XPath Execution Performance with FontoXPath Profiler Source: https://context7.com/fontoxml/fontoxpath/llms.txt This snippet demonstrates how to use the FontoXPath profiler API to measure the execution time of XPath queries. It includes setting up the performance implementation, starting and stopping profiling, executing multiple XPath queries, and retrieving a summary of the performance measurements, which can then be logged or exported to CSV. Dependencies include 'fontoxpath'. ```javascript const { evaluateXPathToNodes, evaluateXPathToString, profiler } = require('fontoxpath'); // Set the Performance API implementation profiler.setPerformanceImplementation(globalThis.performance); // Start profiling profiler.startProfiling(); const doc = new DOMParser().parseFromString( ` ${'value'.repeat(100)} `, 'text/xml' ); // Execute various XPaths for (let i = 0; i < 50; i++) { evaluateXPathToNodes('//item', doc); evaluateXPathToString('string-join(//item, ", ")', doc); evaluateXPathToNodes('//item[position() mod 2 = 0]', doc); } // Stop profiling profiler.stopProfiling(); // Get performance summary const summary = profiler.getPerformanceSummary(); // Results are sorted by total duration (slowest first) summary.forEach(measurement => { console.log(`XPath: ${measurement.xpath}`); console.log(` Times executed: ${measurement.times}`); console.log(` Total duration: ${measurement.totalDuration.toFixed(2)}ms`); console.log(` Average: ${measurement.average.toFixed(2)}ms`); }); // Export to CSV const csv = ['xpath,times,average,totalDuration']; summary.forEach(item => { csv.push(`"${item.xpath}",${item.times},${item.average},${item.totalDuration}`); }); console.log(csv.join('\n')); ``` -------------------------------- ### Create Type-Safe XPath Values with FontoXPath createTypedValueFactory Source: https://context7.com/fontoxml/fontoxpath/llms.txt This example shows how to use the createTypedValueFactory function from FontoXPath to create JavaScript functions that convert values to specific XPath data types (e.g., xs:integer, xs:date, xs:string*). This ensures type safety when passing variables to XPath expressions, preventing unexpected type coercion. Dependencies include 'fontoxpath' and 'domFacade'. ```javascript const { createTypedValueFactory, evaluateXPathToBoolean, domFacade } = require('fontoxpath'); // Create factory for xs:integer type const integerFactory = createTypedValueFactory('xs:integer'); const integerValue = integerFactory(42, domFacade); // The value is recognized as xs:integer const isInteger = evaluateXPathToBoolean( '$value instance of xs:integer', null, null, { value: integerValue } ); console.log(isInteger); // true // Without typed factory, numbers become xs:double const isDouble = evaluateXPathToBoolean( '$value instance of xs:double', null, null, { value: 42 } ); console.log(isDouble); // true // Create factory for xs:date type const dateFactory = createTypedValueFactory('xs:date'); const dateValue = dateFactory(new Date('2024-01-15'), domFacade); const isDate = evaluateXPathToBoolean( '$value instance of xs:date', null, null, { value: dateValue } ); console.log(isDate); // true // Create factory for sequence types const stringSeqFactory = createTypedValueFactory('xs:string*'); const stringSeq = stringSeqFactory(['a', 'b', 'c'], domFacade); const seqResult = evaluateXPathToBoolean( 'count($values) = 3', null, null, { values: stringSeq } ); console.log(seqResult); // true ``` -------------------------------- ### Build and Verify FontoXPath Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Commands to build the project using the Closure Compiler and verify the build against test suites. ```bash npm run build npm run qt3tests -- --dist npm run qt3testsxqueryx -- --dist npm run xqutstests -- --dist npm run xqutstestsxqueryx -- --dist ``` -------------------------------- ### Run Test Suites Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Commands to execute the various test suites available in the project, including general tests and specific XML Query test sets. ```sh npm run test npm run qt3tests npm run xqutstests ``` -------------------------------- ### Publish FontoXPath to NPM Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Standard sequence of commands to version, push tags, and publish the package to the NPM repository. ```bash npm version (major|minor|patch|prerelease) git push git push --tags npm publish ``` -------------------------------- ### Enable Debugging and Tracing Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Shows how to enable the debug option to receive detailed error traces for XPath expressions and how to use fn:trace for logging. ```javascript evaluateXPathToBoolean(`if (true()) then zero-or-one((1, 2)) else (1, 2, 3)`, null, null, null, {debug: true}); ``` -------------------------------- ### Evaluate XPath Expressions Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Demonstrates how to use various evaluation functions like evaluateXPathToBoolean and evaluateXPathToString. It shows how to pass context nodes, variables, and custom namespaces. ```javascript const { evaluateXPath, evaluateXPathToBoolean, evaluateXPathToString, evaluateXPathToFirstNode, evaluateXPathToNumber } = require('fontoxpath'); const documentNode = new DOMParser().parseFromString('', 'text/xml'); console.log(evaluateXPathToBoolean('/xml => exists()', documentNode)); console.log(evaluateXPathToString('$foo', null, null, { foo: 'bar' })); console.log(evaluateXPathToFirstNode('bar', documentNode, null, null, { language: evaluateXPath.XQUERY_3_1_LANGUAGE }).outerHTML); console.log(evaluateXPathToNumber('pi()', documentNode, undefined, {}, { language: evaluateXPath.XQUERY_3_1_LANGUAGE, defaultFunctionNamespaceURI: 'http://www.w3.org/2005/xpath-functions/math' })); ``` -------------------------------- ### Execute Pending Update Lists with Modules Source: https://context7.com/fontoxml/fontoxpath/llms.txt Shows how to register custom XQuery modules containing updating functions and apply the resulting pending update list to a document. This is useful for modularizing complex document transformation logic. ```javascript const { evaluateUpdatingExpressionSync, executePendingUpdateList, registerXQueryModule, evaluateXPath } = require('fontoxpath'); registerXQueryModule(` module namespace ops = "http://example.com/ops"; declare %public %updating function ops:add-timestamp($elem as element()) { insert node attribute timestamp { current-dateTime() } into $elem }; `); const doc = new DOMParser().parseFromString('test', 'text/xml'); const result = evaluateUpdatingExpressionSync( `import module namespace ops = "http://example.com/ops"; ops:add-timestamp(/record)`, doc, null, null, { language: evaluateXPath.XQUERY_UPDATE_3_1_LANGUAGE } ); executePendingUpdateList(result.pendingUpdateList); ``` -------------------------------- ### Execute FontoXPath Test Suites Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Commands to run various test suites including unit tests and compatibility tests. These commands are executed via npm in a Node.js environment. ```bash npm run test npm run qt3tests npm run qt3testsxqueryx npm run xqutstests npm run xqutstestsxqueryx ``` -------------------------------- ### Include and Use XQuery Modules Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Demonstrates how to register and use XQuery modules within FontoXPath. Modules can be registered globally using `registerXQueryModule` and then imported within XPath expressions or made available via the `moduleImports` option. This enables modularity and code reuse for complex XPath queries. ```javascript const fontoxpath = require('fontoxpath'); fontoxpath.registerXQueryModule ( ` module namespace test = "https://www.example.org/test1"; declare %public function test:hello($a) { "Hello " || $a }; `); // Import the module using the XQuery way: fontoxpath.evaluateXPathToString( ` import module namespace test = "https://www.example.org/test1"; (: Invoke the test:hello function :) test:hello('there') `, null, null, null, { language: fontoxpath.evaluateXPath.XQUERY_3_1_LANGUAGE } ); // Or by using the moduleImports API, which can be used in XPath contexts as well fontoxpath.evaluateXPathToString( ` (: Invoke the test:hello function :) test:hello('there') `, null, null, null, { moduleImports: { test: 'https://www.example.org/test1' } } ); ``` -------------------------------- ### Profile XPath Performance Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Demonstrates how to integrate the browser's Performance API with FontoXPath to measure execution time and generate performance summaries. ```javascript import { profiler } from 'fontoxpath'; profiler.setPerformanceImplementation(window.performance); profiler.startProfiling(); const summary = profiler.getPerformanceSummary(); ``` -------------------------------- ### Run FontoXPath Fuzzer Source: https://github.com/fontoxml/fontoxpath/blob/master/CONTRIBUTING.md Command to initiate the fuzzer, which uses a corpus of XPath expressions to perform random mutations and detect bugs. ```bash npm run fuzzer ``` -------------------------------- ### Compile XPath to JavaScript Source: https://context7.com/fontoxml/fontoxpath/llms.txt Illustrates the experimental feature of compiling XPath expressions into native JavaScript functions for improved execution performance. It includes checks for AST acceptance and fallback mechanisms. ```javascript const { compileXPathToJavaScript, executeJavaScriptCompiledXPath, evaluateXPath } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` Phone Novel `, 'text/xml'); const compiledResult = compileXPathToJavaScript( '//product[@category="electronics"]/name', evaluateXPath.NODES_TYPE ); if (compiledResult.isAstAccepted) { const compiledFunction = new Function(compiledResult.code); const nodes = executeJavaScriptCompiledXPath(compiledFunction, doc); console.log(nodes[0].textContent); } ``` -------------------------------- ### Convenience Evaluation Methods Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Helper methods for evaluating XPath expressions that automatically handle specific return types. ```APIDOC ## Convenience Methods ### Description These functions provide shorthand for common return types, such as evaluating to a boolean, string, array, or node list. ### Methods - evaluateXPathToArray - evaluateXPathToAsyncIterator - evaluateXPathToBoolean - evaluateXPathToFirstNode - evaluateXPathToMap - evaluateXPathToNodes - evaluateXPathToNumber - evaluateXPathToNumbers - evaluateXPathToString - evaluateXPathToStrings ### Request Example ```javascript const isVisible = evaluateXPathToBoolean('//element/@visible', contextNode); const firstNode = evaluateXPathToFirstNode('//item', contextNode); ``` ``` -------------------------------- ### Compile XPath to JavaScript for Performance Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Shows how to compile XPath 3.1 queries into JavaScript code for significantly improved execution performance. It covers using `compileXPathToJavaScript` to generate code and `executeJavaScriptCompiledXPath` to run it. This functionality is experimental and supports a subset of XPath 3.1. ```typescript import { compileXPathToJavaScript, CompiledXPathFunction, evaluateXPath, executeJavaScriptCompiledXPath, } from 'fontoxpath'; const documentNode = new DOMParser().parseFromString('

Beep beep.

', 'text/xml'); const compiledXPathResult = compileXPathToJavaScript( '/child::p/text()', evaluateXPath.BOOLEAN_TYPE ); if (compiledXPathResult.isAstAccepted === true) { // Query is compiled succesfully, it can be evaluated. const evalFunction = new Function(compiledXPathResult.code) as CompiledXPathFunction; console.log(executeJavaScriptCompiledXPath(evalFunction, documentNode)); // Outputs: true } else { // Not supported by JS codegen (yet). } ``` -------------------------------- ### Register and Use XQuery Modules in FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Registers XQuery library modules, making their functions and variables available for use in subsequent queries. Modules can import other modules, enabling code organization and reuse. This allows for cleaner syntax when calling module functions and accessing module variables. ```javascript const { registerXQueryModule, evaluateXPathToString, evaluateXPathToNumber, evaluateXPath } = require('fontoxpath'); // Register a module with utility functions registerXQueryModule(` module namespace utils = "http://example.com/utils"; declare %public function utils:format-name($first as xs:string, $last as xs:string) as xs:string { concat($first, " ", $last) }; declare %public function utils:factorial($n as xs:integer) as xs:integer { if ($n le 1) then 1 else $n * utils:factorial($n - 1) }; declare %public variable $utils:version as xs:string := "1.0.0"; `); // Register another module that depends on the first registerXQueryModule(` module namespace app = "http://example.com/app"; import module namespace utils = "http://example.com/utils"; declare %public function app:greet-user($first as xs:string, $last as xs:string) as xs:string { concat("Welcome, ", utils:format-name($first, $last), "!") }; `); const doc = new DOMParser().parseFromString('', 'text/xml'); // Use with XQuery language option const name = evaluateXPathToString( `import module namespace utils = "http://example.com/utils"; utils:format-name("John", "Doe")`, doc, null, null, { language: evaluateXPath.XQUERY_3_1_LANGUAGE } ); console.log(name); // "John Doe" // Use moduleImports option for cleaner syntax const factorial = evaluateXPathToNumber( 'utils:factorial(5)', doc, null, null, { moduleImports: { utils: 'http://example.com/utils' } } ); console.log(factorial); // 120 // Access module variable const version = evaluateXPathToString( '$utils:version', doc, null, null, { moduleImports: { utils: 'http://example.com/utils' } } ); console.log(version); // "1.0.0" ``` -------------------------------- ### Evaluate XQuery Update Expressions Source: https://context7.com/fontoxml/fontoxpath/llms.txt Demonstrates the use of evaluateUpdatingExpressionSync to perform document modifications like inserting, replacing, deleting, and renaming nodes. It highlights the workflow of generating a pending update list and applying it using executePendingUpdateList. ```javascript const { evaluateUpdatingExpressionSync, executePendingUpdateList } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` Aliceactive Bobinactive `, 'text/xml'); const insertResult = evaluateUpdatingExpressionSync( 'insert node Carolactive into /users', doc ); executePendingUpdateList(insertResult.pendingUpdateList); const replaceResult = evaluateUpdatingExpressionSync( 'replace value of node //user[@id="2"]/status with "active"', doc ); executePendingUpdateList(replaceResult.pendingUpdateList); const deleteResult = evaluateUpdatingExpressionSync( 'delete node //user[@id="1"]', doc ); executePendingUpdateList(deleteResult.pendingUpdateList); const renameResult = evaluateUpdatingExpressionSync( 'rename node //user[@id="2"]/name as "fullName"', doc ); executePendingUpdateList(renameResult.pendingUpdateList); ``` -------------------------------- ### Create Typed XPath Values Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Explains how to use the typed value factory to ensure variables are treated as specific XML Schema types (e.g., xs:integer) rather than default JavaScript conversions. ```javascript const integerValueFactory = createTypedValueFactory('xs:integer'); const integerValue = integerValueFactory(123, domFacade); evaluateXPathToBoolean('$value instance of xs:integer', null, null, { value: typedValue }); evaluateXPathToBoolean('$value instance of xs:integer', null, null, { value: 123 }); ``` -------------------------------- ### registerXQueryModule Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Registers an XQuery module globally, allowing it to be imported and used in XPath or XQuery evaluations. ```APIDOC ## registerXQueryModule ### Description Registers an XQuery module string so that its functions and variables can be imported and utilized in subsequent evaluations. ### Parameters - **moduleString** (string) - Required - The full XQuery module definition. ``` -------------------------------- ### executePendingUpdateList Source: https://context7.com/fontoxml/fontoxpath/llms.txt Applies a pending update list to the document, executing all queued modifications. ```APIDOC ## POST /executePendingUpdateList ### Description Applies a pending update list to the document, executing all queued modifications generated by an updating expression. ### Method POST ### Endpoint executePendingUpdateList(pendingUpdateList) ### Parameters #### Request Body - **pendingUpdateList** (Array) - Required - The list of updates returned by evaluateUpdatingExpressionSync. ### Response #### Success Response (200) - **void** - Returns nothing; document is modified in place. ``` -------------------------------- ### evaluateUpdatingExpressionSync Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Evaluates an XQuery Update Facility 3.0 expression synchronously and returns the pending update list and XDM value. ```APIDOC ## evaluateUpdatingExpressionSync ### Description Evaluates an XQuery Update expression against a context node. Returns an object containing the result (xdmValue) and the list of update primitives (pendingUpdateList). ### Method Synchronous Function Call ### Parameters - **xpathExpression** (string) - Required - The XQuery update expression. - **contextNode** (Node) - Optional - The node to evaluate against. - **domFacade** (IDomFacade) - Optional - Interface to access the DOM. - **variables** (Object) - Optional - Variables used in the expression. - **options** (Object) - Optional - Configuration options. ### Response - **xdmValue** (any) - The result of the query. - **pendingUpdateList** (Object[]) - A list of update primitives to be executed. ``` -------------------------------- ### evaluateUpdatingExpressionSync Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XQuery Update Facility expression and returns a pending update list for document modification. ```APIDOC ## POST /evaluateUpdatingExpressionSync ### Description Evaluates an XQuery Update Facility expression and returns both the query result and a pending update list that can be applied to modify the document. ### Method POST ### Endpoint evaluateUpdatingExpressionSync(expression, contextNode, variables, namespaceResolver, options) ### Parameters #### Request Body - **expression** (string) - Required - The XQuery Update expression to evaluate. - **contextNode** (Node) - Required - The DOM node to act as the context. - **variables** (Object) - Optional - External variables used in the expression. - **namespaceResolver** (Function) - Optional - Function to resolve namespaces. - **options** (Object) - Optional - Configuration options including language version. ### Response #### Success Response (200) - **pendingUpdateList** (Array) - A list of pending updates to be applied to the document. - **queryResult** (Any) - The result of the query expression. ``` -------------------------------- ### Evaluate and Execute XQuery Update Expressions Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Evaluates an XQuery Update Facility expression and executes the resulting pending updates. It returns both the updated XML value and a list of pending updates. Dependencies include FontoXPath library. Inputs are an XPath expression, context node, DOM facade, variables, and options. Outputs are an object containing xdmValue and pendingUpdateList. ```javascript evaluateUpdatingExpressionSync(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript executePendingUpdateList(pendingUpdateList, domFacade, nodesFactory, documentWriter); ``` ```javascript const { evaluateUpdatingExpressionSync, executePendingUpdateList } = require('fontoxpath'); const documentNode = new DOMParser().parseFromString('', 'text/xml'); const result = evaluateUpdatingExpressionSync('replace node /xml with ', documentNode) executePendingUpdateList(result.pendingUpdateList); console.log(documentNode.documentElement.outerHTML); // Outputs: ""; ``` ```javascript registerXQueryModule(` module namespace my-custom-namespace = "my-custom-uri"; (:~ Insert attribute somewhere ~:) declare %public %updating function my-custom-namespace:do-something ($ele as element()) as xs:boolean { if ($ele/@done) then false() else (insert node attribute done {"true"} into $ele, true()) }; `); // At some point: const contextNode = null; const pendingUpdatesAndXdmValue = evaluateUpdatingExpressionSync( 'ns:do-something(.)', contextNode, null, null, { moduleImports: { ns: 'my-custom-uri' } } ); console.log(pendingUpdatesAndXdmValue.xdmValue); // this is true or false, see function executePendingUpdateList(pendingUpdatesAndXdmValue.pendingUpdateList, null, null, null); // At this point the context node will have its attribute set ``` -------------------------------- ### executePendingUpdateList Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Executes a list of update primitives returned by an updating expression to modify the DOM. ```APIDOC ## executePendingUpdateList ### Description Applies the changes defined in a pending update list to the DOM using specified factories and writers. ### Parameters - **pendingUpdateList** (Object[]) - Required - The list of updates to apply. - **domFacade** (IDomFacade) - Optional - Interface for DOM access. - **nodesFactory** (INodesFactory) - Optional - Factory for creating new nodes. - **documentWriter** (IDocumentWriter) - Optional - Writer for applying modifications. ``` -------------------------------- ### Convenience XPath Evaluation Functions - FontoXPath Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md A set of convenience functions for evaluating XPath expressions with pre-defined return types. These functions simplify common querying tasks by abstracting the `returnType` parameter of the main `evaluateXPath` function. They all take the same core arguments: `xpathExpression`, `contextNode`, `domFacade`, and `variables`, along with optional `options`. ```javascript evaluateXPathToArray(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToAsyncIterator(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToBoolean(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToFirstNode(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToMap(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToNodes(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToNumber(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToNumbers(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToString(xpathExpression, contextNode, domFacade, variables, options); ``` ```javascript evaluateXPathToStrings(xpathExpression, contextNode, domFacade, variables, options); ``` -------------------------------- ### Evaluate XPath to Nodes with TypeScript Generics Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Demonstrates how to use FontoXPath to evaluate an XPath query and retrieve nodes, utilizing TypeScript generics for type safety with DOM implementations like slimdom.Node. This avoids manual casting and improves code clarity. ```typescript const myNodes = evaluateXPathToNodes('bar', null, null, null, { language: evaluateXPath.XQUERY_3_1_LANGUAGE, }); // Type of myNodes is: slimdom.Node[] . ``` -------------------------------- ### evaluateXPathToFirstNode Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns the first matching node, or null if no match is found. ```APIDOC ## evaluateXPathToFirstNode ### Description Evaluates an XPath expression and returns the first matching node, or null if no match is found. ### Method Function Call ### Parameters #### Arguments - **xpath** (string) - Required - The XPath expression to evaluate. - **contextNode** (Node) - Required - The context node for the evaluation. - **variables** (Object) - Optional - Variables to be used in the XPath expression. ### Request Example const firstUser = evaluateXPathToFirstNode('//user', doc); ### Response - **Node|null** - The first matching node or null. ``` -------------------------------- ### Evaluate XPath to First Node with FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns only the first matching node found. If no nodes match the expression, it returns `null`. This is efficient when you only need one specific element. ```javascript const { evaluateXPathToFirstNode } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` Alice Bob Carol `, 'text/xml'); // Get first user const firstUser = evaluateXPathToFirstNode('//user', doc); console.log(firstUser.getAttribute('id')); // "1" // Get first with condition const firstMember = evaluateXPathToFirstNode('//user[@role="member"]', doc); console.log(firstMember.querySelector('name').textContent); // "Bob" // Returns null when no match const admin = evaluateXPathToFirstNode('//user[@role="superadmin"]', doc); console.log(admin); // null // Using with variables const targetUser = evaluateXPathToFirstNode( '//user[@id = $userId]', doc, null, { userId: '2' } ); console.log(targetUser.querySelector('name').textContent); // "Bob" ``` -------------------------------- ### compileXPathToJavaScript Source: https://context7.com/fontoxml/fontoxpath/llms.txt Compiles an XPath expression to JavaScript code for improved execution performance. ```APIDOC ## POST /compileXPathToJavaScript ### Description Compiles an XPath expression to JavaScript code for improved execution performance. This is experimental and supports a subset of XPath 3.1. ### Method POST ### Endpoint compileXPathToJavaScript(expression, returnType) ### Parameters #### Request Body - **expression** (string) - Required - The XPath expression to compile. - **returnType** (number) - Required - The expected return type (e.g., NODES_TYPE, BOOLEAN_TYPE). ### Response #### Success Response (200) - **isAstAccepted** (boolean) - Whether the expression was successfully compiled. - **code** (string) - The generated JavaScript code if accepted. - **reason** (string) - Reason if compilation failed. ``` -------------------------------- ### Evaluate XPath Expression - FontoXPath Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md The main function to evaluate an XPath expression against a given context node. It supports various return types and options for customization, including namespace resolution and language selection. Dependencies include a DOM facade and optionally variables, a nodes factory, and debug options. ```javascript evaluateXPath(xpathExpression, contextNode, domFacade, variables, returnType, options); ``` -------------------------------- ### evaluateXPath Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md The primary function for evaluating XPath expressions with full control over return types and execution options. ```APIDOC ## evaluateXPath ### Description Evaluates an XPath expression against a context node using a specific DOM facade and configuration options. ### Parameters - **xpathExpression** (String) - Required - The query to evaluate. - **contextNode** (Node) - Optional - The node in which context the expression is evaluated. - **domFacade** (IDomFacade) - Optional - Implementation used for querying the DOM. - **variables** (Object) - Optional - Variables available within the expression. - **returnType** (number) - Optional - Determines the result type (e.g., NUMBER_TYPE, NODES_TYPE). - **options** (Object) - Optional - Configuration including namespaceResolver, nodesFactory, and language. ### Request Example ```javascript evaluateXPath('//someElement', contextNode, domFacade, {}, evaluateXPath.NODES_TYPE, { debug: true }); ``` ``` -------------------------------- ### Evaluate XPath with Custom Return Types Source: https://context7.com/fontoxml/fontoxpath/llms.txt The evaluateXPath function is the primary entry point for executing XPath queries. It supports various return types such as nodes, strings, booleans, and numbers, and allows for variable injection. ```javascript const { evaluateXPath } = require('fontoxpath'); const documentNode = new DOMParser().parseFromString(` JavaScript Guide29.99 XML Handbook39.99 `, 'text/xml'); const allBooks = evaluateXPath('//book', documentNode, null, null, evaluateXPath.NODES_TYPE); const title = evaluateXPath('//book[@id="1"]/title/text()', documentNode, null, null, evaluateXPath.STRING_TYPE); const hasExpensiveBooks = evaluateXPath('//book[price > 30]', documentNode, null, null, evaluateXPath.BOOLEAN_TYPE); const totalPrice = evaluateXPath('sum(//book/price)', documentNode, null, null, evaluateXPath.NUMBER_TYPE); const result = evaluateXPath( '//book[@id = $bookId]/title/string()', documentNode, null, { bookId: '2' }, evaluateXPath.STRING_TYPE ); ``` -------------------------------- ### registerCustomXPathFunction Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Registers a custom function globally, making it available for use in XPath expressions. ```APIDOC ## registerCustomXPathFunction ### Description Registers a new function globally that can be invoked within XPath expressions using its namespace and local name. ### Parameters - **name** ({namespaceURI: string, localName: string}) - Required - The function identifier. - **signature** (string[]) - Required - Array of argument types. - **returnType** (string) - Required - The return type of the function. - **callback** (Function) - Required - The implementation of the function. ``` -------------------------------- ### registerCustomXPathFunction Source: https://context7.com/fontoxml/fontoxpath/llms.txt Registers a custom function that can be called from XPath expressions. Functions must be registered in a custom namespace. ```APIDOC ## registerCustomXPathFunction ### Description Registers a custom function that can be called from XPath expressions. Functions must be registered in a custom namespace. ### Method JavaScript Function Call ### Parameters #### Arguments - **name** (object) - Required - Object containing namespaceURI and localName. - **argumentTypes** (array) - Required - Array of XPath types (e.g., 'xs:string'). - **returnType** (string) - Required - The XPath return type. - **callback** (function) - Required - The implementation function receiving the dynamic context and arguments. ### Request Example registerCustomXPathFunction( { namespaceURI: 'http://example.com/functions', localName: 'greet' }, ['xs:string'], 'xs:string', (dynamicContext, name) => `Hello, ${name}!` ); ### Response #### Success Response - **void** - The function is registered globally for the fontoxpath instance. ``` -------------------------------- ### Evaluate XPath to String Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns the result as a string, effectively performing a string conversion on the output. ```javascript const { evaluateXPathToString } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` John Doe john@example.com `, 'text/xml'); const name = evaluateXPathToString('//name', doc); const greeting = evaluateXPathToString('"Hello, " || //name || "!"', doc); const upperName = evaluateXPathToString('upper-case(//name)', doc); const formatted = evaluateXPathToString( '$prefix || //name/text()', doc, null, { prefix: 'User: ' } ); ``` -------------------------------- ### evaluateXPathToMap Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression that returns an XPath map and converts it to a JavaScript object. ```APIDOC ## evaluateXPathToMap ### Description Evaluates an XPath expression that returns an XPath map and converts it to a JavaScript object. ### Method Function Call ### Parameters #### Arguments - **xpath** (string) - Required - The XPath expression returning a map. - **contextNode** (Node) - Required - The context node. ### Request Example const simpleMap = evaluateXPathToMap('map { "name": "John", "age": 30 }', doc); ### Response - **Object** - A JavaScript object representing the XPath map. ``` -------------------------------- ### evaluateXPathToNodes Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns all matching nodes as an array, preserving document order. ```APIDOC ## evaluateXPathToNodes ### Description Evaluates an XPath expression and returns all matching nodes as an array, preserving the order defined by the XPath. ### Method Function Call ### Parameters #### Arguments - **xpath** (string) - Required - The XPath expression to evaluate. - **contextNode** (Node) - Required - The context node for the evaluation. ### Request Example const allProducts = evaluateXPathToNodes('//product', doc); ### Response - **Array** - An array of nodes matching the expression. ``` -------------------------------- ### evaluateXPathToArray Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression that returns an XPath array and converts it to a JavaScript array. ```APIDOC ## evaluateXPathToArray ### Description Evaluates an XPath expression that returns an XPath array and converts it to a JavaScript array. ### Method Function Call ### Parameters #### Arguments - **xpath** (string) - Required - The XPath expression returning an array. - **contextNode** (Node) - Required - The context node. ### Request Example const simpleArray = evaluateXPathToArray('[1, 2, 3, 4, 5]', doc); ### Response - **Array** - A JavaScript array containing the evaluated values. ``` -------------------------------- ### Register Custom XPath Function Source: https://github.com/fontoxml/fontoxpath/blob/master/README.md Registers a custom XPath function globally within FontoXPath. This allows extending XPath capabilities with user-defined logic. The function takes a name (namespaceURI and localName), signature, return type, and a callback function as arguments. The callback function is executed when the custom function is called within an XPath expression. ```javascript registerCustomXPathFunction(name, signature, returnType, callback); ``` ```javascript const fontoxpath = require('fontoxpath'); // Register a function called 'there' in the 'hello' namespace: fontoxpath.registerCustomXPathFunction( { namespaceURI: 'hello', localName: 'there' }, ['xs:string'], 'xs:string', (_, str) => `Hello there, ${str}` ); // and call it, using the BracedUriLiteral syntax (Q{}) const out = fontoxpath.evaluateXPathToString('Q{hello}there("General Kenobi")'); // Or by using a prefix instead: const URI_BY_PREFIX = { hi: 'hello' }; const out2 = fontoxpath.evaluateXPathToString('hi:there("General Kenobi")', null, null, null, { namespaceResolver: (prefix) => URI_BY_PREFIX[prefix], }); ``` -------------------------------- ### Evaluate XPath to Array with FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression that results in an XPath array and converts it into a standard JavaScript array. Supports creating arrays directly from XPath expressions or sequences. ```javascript const { evaluateXPathToArray } = require('fontoxpath'); const doc = new DOMParser().parseFromString('', 'text/xml'); // Create array with array constructor const simpleArray = evaluateXPathToArray('[1, 2, 3, 4, 5]', doc); console.log(simpleArray); // [1, 2, 3, 4, 5] // Nested arrays const nestedArray = evaluateXPathToArray('[[1, 2], [3, 4]]', doc); console.log(nestedArray); // [[1, 2], [3, 4]] // Array from sequence const fromSequence = evaluateXPathToArray('array { 1 to 5 }', doc); console.log(fromSequence); // [1, 2, 3, 4, 5] // Array with string values const stringArray = evaluateXPathToArray('["apple", "banana", "cherry"]', doc); console.log(stringArray); // ["apple", "banana", "cherry"] ``` -------------------------------- ### Register Custom XPath Functions in FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Registers custom functions that can be invoked within XPath expressions. These functions must be defined within a specific namespace and can accept various data types as arguments, returning a specified type. They can interact with the DOM or perform calculations. ```javascript const { registerCustomXPathFunction, evaluateXPathToString, evaluateXPathToNumber } = require('fontoxpath'); // Register a simple string function registerCustomXPathFunction( { namespaceURI: 'http://example.com/functions', localName: 'greet' }, ['xs:string'], 'xs:string', (dynamicContext, name) => `Hello, ${name} அளிக்க!` ); // Register a numeric calculation function registerCustomXPathFunction( { namespaceURI: 'http://example.com/functions', localName: 'calculateTax' }, ['xs:decimal', 'xs:decimal'], 'xs:decimal', (dynamicContext, amount, rate) => amount * rate ); // Register a function that accesses the DOM registerCustomXPathFunction( { namespaceURI: 'http://example.com/functions', localName: 'getElementCount' }, ['element()'], 'xs:integer', (dynamicContext, element) => element.childNodes.length ); const doc = new DOMParser().parseFromString('', 'text/xml'); // Call using Q{} (BracedURILiteral) syntax const greeting = evaluateXPathToString('Q{http://example.com/functions}greet("World")', doc); console.log(greeting); // "Hello, World!" const tax = evaluateXPathToNumber('Q{http://example.com/functions}calculateTax(100, 0.08)', doc); console.log(tax); // 8 // Call using namespace resolver const count = evaluateXPathToNumber( 'ex:getElementCount(/root)', doc, null, null, { namespaceResolver: prefix => prefix === 'ex' ? 'http://example.com/functions' : null } ); console.log(count); // 2 ``` -------------------------------- ### Evaluate XPath to Nodes with FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns all matching nodes as a JavaScript array. Preserves the order defined by the XPath. Useful for retrieving multiple elements or attributes that match a specific query. ```javascript const { evaluateXPathToNodes } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` Phone Novel Laptop `, 'text/xml'); // Get all products const allProducts = evaluateXPathToNodes('//product', doc); console.log(allProducts.length); // 3 // Filter by attribute const electronics = evaluateXPathToNodes('//product[@category="electronics"]', doc); console.log(electronics.length); // 2 console.log(electronics[0].querySelector('name').textContent); // "Phone" // Get specific children const names = evaluateXPathToNodes('//product/name', doc); names.forEach(node => console.log(node.textContent)); // "Phone" // "Novel" // "Laptop" // Union operator (document order) const mixed = evaluateXPathToNodes('//product[@category="books"] | //product[@category="electronics"]', doc); console.log(mixed.length); // 3 (sorted in document order) ``` -------------------------------- ### Indeterminate SequenceType Annotation in FontoXPath Source: https://github.com/fontoxml/fontoxpath/blob/master/src/typeInference/README.md This snippet shows the SequenceType used when node types are indeterminate during annotation, either because they are concrete only at runtime or due to limitations in type inference. This fallback ensures execution proceeds smoothly. ```javascript { type: ValueType.ITEM, mult: SequenceMultiplicity.ZERO_OR_MORE } (or item()* for short) ``` -------------------------------- ### FontoXPath CSS Styling Source: https://github.com/fontoxml/fontoxpath/blob/master/demo/index.html This snippet defines CSS rules for the FontoXPath interface, specifically styling an XML file selector and an XPath input field. It sets basic display properties, margins, borders, and height for the XML file element, and full width for the XPath field. ```CSS fontoxpath #xmlFile * { all: initial; display: block; margin: 5px; border: 1px solid black; min-height: 5px; } #xpathField { width: 100%; } ``` -------------------------------- ### Evaluate XPath to Map with FontoXPath Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression that results in an XPath map and converts it into a JavaScript object. This function is useful for transforming structured data from XPath maps into a more accessible JavaScript object format. ```javascript const { evaluateXPathToMap } = require('fontoxpath'); const doc = new DOMParser().parseFromString('', 'text/xml'); // Create map with map constructor const simpleMap = evaluateXPathToMap('map { "name": "John", "age": 30 }', doc); console.log(simpleMap); // { name: "John", age: 30 } // Nested maps const nestedMap = evaluateXPathToMap('map { "user": map { "id": 1, "active": true() } }', doc); console.log(nestedMap); // { user: { id: 1, active: true } } // Map with numeric keys const numericKeys = evaluateXPathToMap('map { 1: "one", 2: "two" }', doc); console.log(numericKeys['1']); // "one" (note: JS converts keys to strings) // Map from data const dataDoc = new DOMParser().parseFromString('', 'text/xml'); const dataMap = evaluateXPathToMap('map { //item/@key/string(): //item/@value/string() }', dataDoc); console.log(dataMap); // { status: "active" } ``` -------------------------------- ### Evaluate XPath to Number Source: https://context7.com/fontoxml/fontoxpath/llms.txt Evaluates an XPath expression and returns a numeric result, useful for calculations and counting operations. ```javascript const { evaluateXPathToNumber } = require('fontoxpath'); const doc = new DOMParser().parseFromString(` 210.50 35.25 `, 'text/xml'); const itemCount = evaluateXPathToNumber('count(//item)', doc); const totalPrice = evaluateXPathToNumber('sum(//item/price)', doc); const totalQty = evaluateXPathToNumber('sum(//item/qty)', doc); const discountedTotal = evaluateXPathToNumber( 'sum(//item/price) * (1 - $discount)', doc, null, { discount: 0.1 } ); ``` -------------------------------- ### Evaluate XPath to Boolean Source: https://context7.com/fontoxml/fontoxpath/llms.txt A convenience function that returns a boolean result based on the effective boolean value of the provided XPath expression. ```javascript const { evaluateXPathToBoolean } = require('fontoxpath'); const doc = new DOMParser().parseFromString('', 'text/xml'); const hasItem = evaluateXPathToBoolean('//item', doc); const isActive = evaluateXPathToBoolean('//item[@active = "true"]', doc); const hasMultipleItems = evaluateXPathToBoolean('count(//item) > 1', doc); const matchesId = evaluateXPathToBoolean( '//*[@id = $targetId]', doc, null, { targetId: 'main' } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.