如何使用SXD XPath迭代节点集并打印出每个值?

如何使用SXD XPath迭代节点集并打印出每个值?,xpath,rust,Xpath,Rust,我一直在尝试使用查询XML,但似乎不知道如何处理节点集 板条箱和使用 extern crate sxd_document; extern crate sxd_xpath; use sxd_document::parser; use sxd_xpath::{Factory, Context, Value}; 实际代码 let package = parser::parse("<feed><title>hest</title><title>hest

我一直在尝试使用查询XML,但似乎不知道如何处理节点集

板条箱和使用

extern crate sxd_document;
extern crate sxd_xpath;

use sxd_document::parser;
use sxd_xpath::{Factory, Context, Value};
实际代码

let package = parser::parse("<feed><title>hest</title><title>hest2</title><title>hest3</title><title>hest4</title></feed>").expect("failed to parse XML");
let document = package.as_document();

let factory = Factory::new();
let xpath = factory.build("/feed/title").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");
let package=parser::parse(“hesthest2hest3hest4”)。expect(“解析XML失败”);
让document=package.as_document();
让factory=factory::new();
让xpath=factory.build(“/feed/title”).expect(“无法编译xpath”);
设xpath=xpath.expect(“未编译xpath”);
让context=context::new();
让value=xpath.evaluate(&context,document.root()).expect(“xpath求值失败”);
我想迭代每个节点并打印出
的值,但我不知道如何做

我是铁锈世界的新手,来自C#和Python。

返回一个

fn evaluate<'d, N>(
    &self,
    context: &Context<'d>,
    node: N,
) -> Result<Value<'d>, ExecutionError>
where
    N: Into<Node<'d>>,
实现为迭代器
,因此您可以在
for
循环中使用它:

for node in nodes {
    // ...
}
每一个产生的价值都将是一个。这是XML文档中所有不同类型节点的枚举。您对
元素
s感兴趣。如果您只关心元素的字符串值,那么可以使用。这隐藏了多个子节点的复杂性,每个子节点都有自己的文本:

println!("{}", node.string_value());
综合起来:

if let Value::Nodeset(nodes) = value {
    for node in nodes {
        println!("{}", node.string_value());
    }
}
Nodeset
没有保证的顺序,因此如果您希望节点按文档中的顺序排列,可以调用:


免责声明:我是SXD文档和SXD XPath的作者

,帮助并感谢详细的回答。很好地处理了doucment\u顺序,但是在我的例子中,元素的顺序不那么重要。
if let Value::Nodeset(nodes) = value {
    for node in nodes {
        println!("{}", node.string_value());
    }
}
if let Value::Nodeset(nodes) = value {
    for node in nodes.document_order() {
        println!("{}", node.string_value());
    }
}