给定以下 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>
有帮助吗?

解决方案

我定义一个键来索引人员:

<xsl:key name="people" match="person" use="login_name" />

此处使用密钥只是保持代码整洁,但如果您经常需要检索密钥,您可能还会发现它有助于提高效率 <person> 元素基于他们的 <login_name> 孩子。

我有一个模板,它返回给定的格式化名称 <person>:

<xsl:template match="person" mode="name">
  <xsl:value-of select="concat(first, ' ', last)" />
</xsl:template>

然后我会这样做:

<xsl:template match="current/login_name">
  <xsl:apply-templates select="key('people', .)" mode="name" />
</xsl:template>

其他提示

你要 current() 功能

<xsl:template match="current/login_name">
  <xsl:value-of select="../../people/person[login_name = current()]/first"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../../people/person[login_name = current()]/last"/>
</xsl:template>

或者更干净一点:

<xsl:template match="current/login_name">
  <xsl:for-each select="../../people/person[login_name = current()]">
    <xsl:value-of select="first"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="last"/>
  </xsl:for-each>
</xsl:template>

如果需要访问多个用户,那么 杰尼特的 <xsl:key /> 方法 是理想的。

这是我的另一种看法:

<xsl:template match="current/login_name">
    <xsl:variable name="person" select="//people/person[login_name = .]" />
    <xsl:value-of select="concat($person/first, ' ', $person/last)" />
</xsl:template>

我们分配选定的 <person> 节点到变量,然后我们使用 concat() 函数输出名字/姓氏。

您的示例 XML 中也存在错误。这 <person> 节点错误地以以下内容结尾 </preson> (错字)

如果我们知道 XML 文档的整体结构(带有根节点等),就可以给出更好的解决方案

我认为他真正想要的是“当前”节点的匹配中的替换,而不是人员节点中的匹配:

<xsl:variable name="login" select="//current/login_name/text()"/>

<xsl:template match="current/login_name">
<xsl:value-of select='concat(../../people/person[login_name=$login]/first," ", ../../people/person[login_name=$login]/last)'/>

</xsl:template>

只是将我的想法添加到堆栈中

<xsl:template match="login_name[parent::current]">
 <xsl:variable name="login" select="text()"/>
 <xsl:value-of select='concat(ancestor::people/child::person[login_name=$login]/child::first/text()," ",ancestor::people/child::person[login_name=$login]/child::last/text())'/>
</xsl:template>

我总是更喜欢在 XPath 中显式使用轴,恕我直言,更冗长但更清晰。

根据 XML 文档的其余部分的外观(假设这只是一个片段),您可能需要限制对“ancestor::people”的引用,例如使用“ancestor::people[1]”来限制对第一个人的引用祖先。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top