Skip to main content

Module xpath

Module xpath 

Source
Expand description

Provide APIs for compiling and evaluating XPath.

The current implementation supports only XPath 1.0.

§Example

use anyxml::xpath::evaluate_str;

const DOCUMENT: &str = r#"<root>
    <greeting xml:lang='en'>Hello</greeting>
    <greeting xml:lang='ja'>こんにちは</greeting>
    <greeting xml:lang='ch'>你好</greeting>
</root>
"#;
const XPATH: &str = "//greeting[lang('ja')]/text()";

let text = evaluate_str(XPATH, DOCUMENT, None)
    .unwrap()
    .as_string()
    .unwrap();
assert_eq!(text.as_ref(), "こんにちは");

If a single expression is reused multiple times, it can be precompiled using the compile function.

use anyxml::{
    sax::parser::XMLReaderBuilder,
    tree::TreeBuildHandler,
    xpath::compile,
};

const DOCUMENT: &str = r#"<root>
    <greeting xml:lang='en'>Hello</greeting>
    <greeting xml:lang='ja'>こんにちは</greeting>
    <greeting xml:lang='ch'>你好</greeting>
</root>
"#;
const XPATH: &str = "//greeting[lang('ja')]/text()";

let mut reader = XMLReaderBuilder::new()
    .set_handler(TreeBuildHandler::default())
    .build();
reader.parse_str(DOCUMENT, None).unwrap();
let document = reader.handler.document;

let mut expression = compile(XPATH).unwrap();
let text = expression.evaluate(document)
    .unwrap()
    .as_string()
    .unwrap();
assert_eq!(text.as_ref(), "こんにちは");

Structs§

XPathContext
XPath evaluation context.
XPathExpression
Precompiled XPath expression.
XPathNodeSet

Enums§

XPathCompileError
XPathError
XPathObject
XPath object types.

Functions§

compile
Compile xpath as a XPath expression.
evaluate
Evaluate xpath as an XPath expression with document as the initial context node.
evaluate_reader
Parse the XML documents using reader as the source and evaluate xpath as an XPath expression.
evaluate_str
Parse xml as the XML document and evaluate xpath as an XPath expression.
evaluate_uri
Parse the XML document where uri is the base URI of the source, and evaluate xpath as an XPath expression.