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

How to evaluate from specified node? #141

Open
Magicloud opened this issue Jun 9, 2023 · 0 comments
Open

How to evaluate from specified node? #141

Magicloud opened this issue Jun 9, 2023 · 0 comments

Comments

@Magicloud
Copy link

I have a doc like following. I want to extract the text of "abc" and "def", when text of node "b" starts with "a". I first used a XPath /root/a/b[starts-with(text(), 'a')]/.. to get to node "a". Then evaluate //a/b/text() and //a/c/text() on node "a". Surprisingly it returned content of a's sibling. What should I do?

<root>
  <other-node-with-same-structure></other-node-with-same-structure>
  <a>
    <b>abc</b>
    <c>def</c>
  </a>
  <other-node-with-same-structure></other-node-with-same-structure>
</root>

Rust code:

    let xpath_factory = sxd_xpath::Factory::new();
    let b = xpath_factory.build("//a/b/text()")?.unwrap();
    let c = xpath_factory.build("//a/c/text()")?.unwrap();
    let xdoc: sxd_document::Document = todo!();
    let matches = sxd_xpath::evaluate_xpath(
        &xdoc,
        "/root/a/b[starts-with(text(), 'a')]/..",
    )?;
    if let sxd_xpath::Value::Nodeset(nodes) = matches {
        nodes
            .iter()
            .map(|i| {
                let context = sxd_xpath::Context::new();
                let b_text = if let sxd_xpath::Value::Nodeset(bs) = b.evaluate(&context, i)? {
                    bs.iter()
                        .next()
                        .map(|x| x.string_value())
                        .unwrap_or_default()
                } else {
                    "".to_string()
                };
                let c_text = if let sxd_xpath::Value::Nodeset(cs) = c.evaluate(&context, i)? {
                    cs.iter()
                        .next()
                        .map(|x| x.string_value())
                        .unwrap_or_default()
                } else {
                    "".to_string()
                };
            })
            .collect::<Result<_>>()?;
    }
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

1 participant