Expand description
SXD-XPath
This is a pure-Rust implementation of XPath, a language for addressing parts of an XML document. It aims to implement version 1.0 of the XPath specification.
XPath is wonderful for quickly navigating the complicated hierarchy that is present in many XML documents while having a concise syntax.
Examples
The quickest way to evaluate an XPath against an XML document is
to use evaluate_xpath
.
extern crate sxd_document;
extern crate sxd_xpath;
use sxd_document::parser;
use sxd_xpath::{evaluate_xpath, Value};
fn main() {
let package = parser::parse("<root>hello</root>").expect("failed to parse XML");
let document = package.as_document();
let value = evaluate_xpath(&document, "/root").expect("XPath evaluation failed");
assert_eq!("hello", value.string());
}
Evaluating an XPath returns a Value
, representing the
primary XPath types.
For more complex needs, XPath parsing and evaluation can be split apart. This allows the user to specify namespaces, variables, extra functions, and which node evaluation should begin with. You may also compile an XPath once and reuse it multiple times.
Parsing is handled with the Factory
and evaluation relies on
the Context
. Similar functionality to above can be
accomplished:
extern crate sxd_document;
extern crate sxd_xpath;
use sxd_document::parser;
use sxd_xpath::{Factory, Context, Value};
fn main() {
let package = parser::parse("<root>hello</root>")
.expect("failed to parse XML");
let document = package.as_document();
let factory = Factory::new();
let xpath = factory.build("/root").expect("Could not compile XPath");
let xpath = xpath.expect("No XPath was compiled");
let context = Context::new();
let value = xpath.evaluate(&context, document.root())
.expect("XPath evaluation failed");
assert_eq!("hello", value.string());
}
See Context
for details on how to customize the
evaluation of the XPath.
Programmatically-created XML
The XPath specification assumes certain properties about the XML being processed. If you are processing XML that was parsed from text, this will be true by construction. If you have programmatically created XML, please note the following cases.
Namespaces
If you have programmatically created XML with namespaces but not defined prefixes, some XPath behavior may be confusing:
- The
name
method will not include a prefix, even if the element or attribute has a namespace. - The
namespace
axis will not include namespaces without prefixes.
Document order
If you have programmatically created XML but not attached the nodes to the document, some XPath behavior may be confusing:
- These nodes have no document order. If you create a variable containing these nodes and apply a predicate to them, these nodes will appear after any nodes that are present in the document, but the relative order of the nodes is undefined.
Re-exports
pub use context::Context;