Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document xpath with namespace example. #138

Open
madelaney opened this issue Apr 29, 2021 · 3 comments
Open

Document xpath with namespace example. #138

madelaney opened this issue Apr 29, 2021 · 3 comments

Comments

@madelaney
Copy link

All,

I'm trying to use sxd-xpath (v0.4), in a static XML file with namespaces defined. I was wondering if it would be possible to create a basic example that shows how to find elements within a given namespace.

  • Mike D.
@kmkaplan
Copy link

There's an example of using namespace in the documentation for sxd_xpath::context::Context

@thomas725
Copy link

thomas725 commented May 22, 2023

If I take the most basic sample from your docs and add an xmlns attribute to the root tag, value.string() gives an empty string instead of the expected "hello".

fn xpath_example() {
    let package = parser::parse("<root xmlns=\"https://some.place.com/metadata\">hello</root>").expect("failed to parse XML");
    let document = package.as_document();

    let value = evaluate_xpath(&document, "/root").expect("XPath evaluation failed");
    println!("{}", value.string());
    assert_eq!("hello", value.string());
}

@AHSauge
Copy link

AHSauge commented Jun 30, 2023

Indeed, that's due to the namespace. From experience, evaluate_xpath won't work with that. Instead, you need to make yourself a context as suggested in the comment prior

fn xpath_example() {
    let package = parser::parse("<root xmlns=\"https://some.place.com/metadata\">hello</root>").expect("failed to parse XML");
    let document = package.as_document();
    let mut context = Context::new();
    context.set_namespace("foobar", "https://some.place.com/metadata");
    let xpath = Factory::new().build("/foobar:root").expect("Unable to build xpath").expect("Unable to build xpath");
    let value = xpath.evaluate(&context, document.root()).expect("XPath evaluation failed");

    println!("{}", value.string());
    assert_eq!("hello", value.string());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants