Struct sxd_xpath::context::Context
[−]
[src]
pub struct Context<'d> { /* fields omitted */ }
Contains the context in which XPath expressions are executed. The context contains functions, variables, and namespace mappings.
Examples
A complete example showing all optional settings.
extern crate sxd_document; extern crate sxd_xpath; use std::collections::HashMap; use sxd_document::parser; use sxd_xpath::{Factory, Context, Value}; use sxd_xpath::{context, function}; struct Sigmoid; impl function::Function for Sigmoid { fn evaluate<'c, 'd>(&self, _context: &context::Evaluation<'c, 'd>, args: Vec<Value<'d>>) -> Result<Value<'d>, function::Error> { let mut args = function::Args(args); args.exactly(1)?; let val = args.pop_number()?; let computed = (1.0 + (-val).exp()).recip(); Ok(Value::Number(computed)) } } fn main() { let package = parser::parse("<thing xmlns:ns0='net:brain' ns0:bonus='1' />") .expect("failed to parse XML"); let document = package.as_document(); let node = document.root().children()[0]; let mut context = Context::new(); context.set_function("sigmoid", Sigmoid); context.set_variable("t", 2.0); context.set_namespace("neural", "net:brain"); let xpath = "sigmoid(@neural:bonus + $t)"; let factory = Factory::new(); let xpath = factory.build(xpath).expect("Could not compile XPath"); let xpath = xpath.expect("No XPath was compiled"); let value = xpath.evaluate(&context, node).expect("XPath evaluation failed"); assert_eq!(0.952, (value.number() * 1000.0).trunc() / 1000.0); }
Note that we are using a custom function (sigmoid
), a variable
($t
), and a namespace (neural:
). The current node is passed to
the evaluate
method and is not the root of the tree but the
top-most element.
Methods
impl<'d> Context<'d>
[src]
fn new() -> Self
Registers the core XPath 1.0 functions.
fn without_core_functions() -> Self
No functions, variables or namespaces will be defined.
fn set_function<N, F>(&mut self, name: N, function: F) where
N: Into<OwnedQName>,
F: Function + 'static,
N: Into<OwnedQName>,
F: Function + 'static,
Register a function within the context
fn set_variable<N, V>(&mut self, name: N, value: V) where
N: Into<OwnedQName>,
V: Into<Value<'d>>,
N: Into<OwnedQName>,
V: Into<Value<'d>>,
Register a variable within the context
fn set_namespace(&mut self, prefix: &str, uri: &str)
Register a namespace prefix within the context