英文:
Single expression to get combined parent+child attributes?
问题
I'm providing the translated code part without any additional content as you requested:
假设我有这样的文档:
<sentence group="A">
<word type="1"/>
<word type="2"/>
</sentence>
<sentence group="B">
<word type="1"/>
</sentence>
...并且我想要输出如下:
"A-1"
"A-2"
"B-1"
是否有一个单一的XPath表达式可以返回这个结果?请注意,输出的确切形式不是必要的,主要是父子属性的组合。
编辑:我的问题实际上应该包括所需的XPath版本,而在我这种情况下不幸的是是1.0版本。所以我接受了 @Michael Kay 的回答,他澄清了在1.0版本中无法完成这个任务。
请注意,@Fravadona 的建议可能适用于XPath 2.0。
英文:
Suppose I have a document like this:
<sentence group="A">
<word type="1"/>
<word type="2"/>
</sentence>
<sentence group="B">
<word type="1"/>
</sentence>
...and I want output like this:
"A-1"
"A-2"
"B-1"
Is there a single xpath expression that would return this? Note the exact form of output is not essential, the main thing is the combination of parent-child attributes.
EDIT: My question really should have included desired xpath version, which in my case unfortunately is 1.0. So I accepted @Michael Kay's answer that clarified that it cannot be done in version 1.0.
Note @Fravadona's suggestion might work for xpath 2.0.
答案1
得分: 2
XPath 1.0中无法完成此操作,原因如下:
- XPath 1.0没有用于字符串集合或序列的数据类型
- 无法将结果返回为节点集,因为结果中所需的值并不是输入中存在的节点的值
- XPath 1.0没有类似于string-join的函数,可以从一组输入字符串形成单个字符串。
@Fravadona提供了一个在XPath 2.0中可以工作的答案。
英文:
I don't think this can be done in XPath 1.0, for the following reasons:
- XPath 1.0 does not have a data type for a set or sequence of strings
- You can't return the result as a nodeset because the values you want in the result are not the values of nodes that exist in the input
- XPath 1.0 does not have a function like string-join to form a single string from a set of input strings.
@Fravadona has supplied an answer that will work in XPath 2.0.
答案2
得分: 1
如果您可以使用XPath 2.0,则以下表达式应该实现您想要的效果:
//word/concat(parent::sentence/@group,"-",@type)
对于每个 word
节点,连接:
- 其
sentence
父节点的group
属性 - 一个破折号
- 其
type
属性。
英文:
If you can use XPath 2.0 then the following expression should do what you want:
//word/concat(parent::sentence/@group,"-",@type)
for each word
node, concatenate:
- the
group
attribute of itssentence
parent-node - a dash
- its
type
attribute.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论