【问题标题】:XPath/XSLT: A sequence of more than one item is not allowed as the first sort keyXPath/XSLT:不允许将多个项目的序列作为第一个排序键
【发布时间】:2018-11-04 19:22:10
【问题描述】:

你好 stackoverflow 社区,

我正在尝试按嵌套属性排序,但一直收到错误提示

XPTY0004:一个以上项目的序列不允许作为第一个排序键。

这具体发生在一行

order by $x/role/@startdate

来自以下代码

<result>{
  for $x in /congress/people/person
  where $x/role[@type = 'sen' and @current = 1 and @state = 'NC']
  order by $x/role/@startdate
  return <senator name="{$x/@name}"/>
 }</result>

我想知道您如何正确地按嵌套属性排序。

编辑:

这是 XML 文档的一些示例代码

<congress>
  <people>
    <person birthday="1952-11-09" gender="M" id="B000944" name="Sherrod Brown">
      <role district="13" enddate="1995-01-03" party="Democrat" startdate="1993-01-05" state="OH" type="rep"/>
      <role district="13" enddate="1997-01-03" party="Democrat" startdate="1995-01-04" state="OH" type="rep"/>
      <role enddate="2007-01-03" party="Democrat" startdate="2001-01-03" state="WA" type="sen"/>
      <role enddate="2013-01-03" party="Democrat" startdate="2007-01-04" state="WA" type="sen"/>
      <role current="1" enddate="2019-01-03" party="Democrat" startdate="2013-01-03" state="WA" type="sen"/>
    </person>
    <person>
      ...
    </person>
  </people>
</congress>

【问题讨论】:

  • 如果要选择属性节点需要使用$x/role/@startdate。即使那样,如果有多个 role 元素具有该属性,您也会收到该错误。向我们展示输入样本,并说明如果有多个属性,您要选择哪个属性。 XQuery 3.1 有一个sort 函数,您可以使用sort(/congress/people/person[role[@type = 'sen' and @current = 1 and @state = 'NC']], (), function($p) { $p/role/@startdate }) 对所有属性进行排序。
  • 您需要使用特定的rolestartdate 属性(例如$x/role[1]/@startdate$x/role[@current = 1]/@startdate),或者您确实需要sort 函数。
  • "...那么,您想分别按哪个 role/@startdate 排序?" 是错误消息提出的问题。每个人的第一个角色?最后? @startdate最高的那个? (不一定与“最后一个”相同)“当前”角色?

标签: xml xslt xpath xquery


【解决方案1】:

在您的代码中

for $x in /congress/people/person
  where $x/role[@type = 'sen' and @current = 1 and @state = 'NC']
  order by $x/role/@startdate

我怀疑(尽管我在猜测)您想按与where 条件匹配的role 中的@startdate 进行排序。如果你确信只有一个这样的角色,那么你可以写

for $x in /congress/people/person
let $role := $x/role[@type = 'sen' and @current = 1 and @state = 'NC']
where exists($role)
order by $role/@startdate

如果有多个角色满足谓词的可能性,那么您仍然需要以某种方式指示您要按哪些角色的开始日期进行排序。

【讨论】:

  • 在这种情况下使用for $r in /congress/people/person/role[@type = 'sen' and @current = 1 and @state = 'NC'] 并从那里使用select 父节点不是更容易吗?这将解决歧义。
  • 谢谢。这行得通。感谢大家的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多