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]

Registers the core XPath 1.0 functions.

No functions, variables or namespaces will be defined.

Register a function within the context

Register a variable within the context

Register a namespace prefix within the context

Trait Implementations

impl<'d> Default for Context<'d>
[src]

Returns the "default value" for a type. Read more