【问题标题】:Is there a way to assign a variable in XPath?有没有办法在 XPath 中分配一个变量?
【发布时间】:2013-05-07 15:37:06
【问题描述】:

仅使用 XPath 是否可以执行以下操作?我想在 1.0 中找到一种方法,我认为在 1.0 中不可能。

例子

<test>
  <title>title1</title>
  <title>title2</title>
  <title>title3</title>
  <creator>creator1</creator>
  <creator>creator2</creator>
</test>

我想要以下输出:

title1 creator1
title2 creator2
title3

我认为这可能更适合 xquery,但我不确定,因为我从未使用过它。将 xquery 添加到我当前的应用程序以及我为什么要避免这样做需要做很多工作。我想出的最接近工作的方法是使用

/test/title/fn:string-join( (text(), /test/creator/text()[position()]), ' ')

问题是我在这个例子中找到了所有的创建者。我想知道是否有某种方法可以获取当前位置并为创建者设置位置?我知道如何在 xslt 中轻松做到这一点,但这不是我的选择。

【问题讨论】:

标签: xpath xpath-2.0


【解决方案1】:

这在 XPath 1.0 中是不可能的。在 XQuery(1.0 很好)和 XPath 2.0 中,您都可以这样做:

for $i in 1 to max((count(//title), count(//creator)))
return string-join((//title[$i], //creator[$i]), ' ')

【讨论】:

  • 谢谢。虽然这确实会导致所有内容都成为一个项目而不是分开。
  • 只需删除string-join 并为每个标题和创建者调用/data(),您将获得文本节点的序列。如果您想要输出中的标签,只需删除 string-join 调用。 :) 请在您下次提问时准确指定预期输出,然后您将在第一时间得到您正在寻找的答案。
  • 对不起,虽然我做到了。您给出的示例返回一个结果 title1 creator1 title2 creator2 title3 。我只是认为新行很清楚,我希望将数据分开,或者用 saxen 术语来说是多个 XdmItems。再次感谢。
  • 我刚刚意识到您在降价源中使用了多行。您是否能够完全满足您的需求?
  • 是的,我最终使用了:for $i in 1 to max((count(/test/title), count(/test/creator))) return string-join((/test/title [$i]/text(), /test/creator[$i]/text()),' ')
猜你喜欢
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多