Skip to content

How to evaluate from specified node? #141

@Magicloud

Description

@Magicloud

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<_>>()?;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions