根据当前节点值有条件匹配
给定以下 XML:
<current>
<login_name>jd</login_name>
</current>
<people>
<person>
<first>John</first>
<last>Doe</last>
<login_name>jd</login_name>
</preson>
<person>
<first>Pierre</first>
<last>Spring</last>
<login_name>ps</login_name>
</preson>
</people>
如何从当前/登录匹配器中获取“John Doe”?
我尝试了以下方法:
<xsl:template match="current/login_name">
<xsl:value-of select="../people/first[login_name = .]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
Given the following XML:
<current>
<login_name>jd</login_name>
</current>
<people>
<person>
<first>John</first>
<last>Doe</last>
<login_name>jd</login_name>
</preson>
<person>
<first>Pierre</first>
<last>Spring</last>
<login_name>ps</login_name>
</preson>
</people>
How can I get "John Doe" from within the current/login matcher?
I tried the following:
<xsl:template match="current/login_name">
<xsl:value-of select="../people/first[login_name = .]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我定义一个键来索引人员:
这里使用键只是保持代码干净,但如果您经常需要检索
,您可能还会发现它有助于提高效率基于其
子元素的元素。我有一个模板,它返回给定
的格式化名称:然后我会这样做:
I'd define a key to index the people:
Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the
<person>
elements based on their<login_name>
child.I'd have a template that returned the formatted name of a given
<person>
:And then I'd do:
您想要
current()
函数或一点更干净:
You want
current()
functionor a bit more cleaner:
如果您需要访问多个用户,那么 JeniT 的
方法 是理想的。这是我的替代方案:
我们将选定的
节点分配给一个变量,然后使用concat()
函数输出名字/姓氏。您的示例 XML 中也存在错误。
节点错误地以结尾(拼写错误)
如果我们知道 XML 文档的整体结构(以根为根),可以给出更好的解决方案节点等)
If you need to access multiple users, then JeniT's
<xsl:key />
approach is ideal.Here is my alternative take on it:
We assign the selected
<person>
node to a variable, then we use theconcat()
function to output the first/last names.There is also an error in your example XML. The
<person>
node incorrectly ends with</preson>
(typo)A better solution could be given if we knew the overall structure of the XML document (with root nodes, etc.)
我认为他真正想要的是“当前”节点的匹配中的替换,而不是人员节点中的匹配:
I think what he actually wanted was the replacement in the match for the "current" node, not a match in the person node:
只是为了将我的想法添加到堆栈中,
我总是更喜欢在 XPath 中显式使用轴,恕我直言,更冗长但更清晰。
根据 XML 文档的其余部分的外观(假设这只是一个片段),您可能需要限制对“ancestor::people”的引用,例如使用“ancestor::people[1]”来限制对第一个人的引用祖先。
Just to add my thoughts to the stack
I always prefer to use the axes explicitly in my XPath, more verbose but clearer IMHO.
Depending on how the rest of the XML documents looks (assuming this is just a fragment) you might need to constrain the reference to "ancestor::people" for example using "ancestor::people[1]" to constrain to the first people ancestor.