xslt 从 xml 节点值嵌套 select

xslt nested select from xml node value

我已经查看了其他一些关于嵌套选择的帖子,但我认为它们没有解决我的用例。本质上,我试图通过网络服务在另一个系统中创建一个用户帐户,并且需要传递一个登录 ID,该登录 ID 来自我的 xml 中的一个字段,它基本上可以是任何东西,例如员工 ID、电子邮件地址、 UUID 等。要使用的字段将来自 xml 生成中的配置值。为了简单起见,我已经缩写了我的 xml 和 xslt,所以请不要建议我使用 choose 或 if 语句,因为我需要保持可能的 xml 字段以供选择。

样本XML:

<root>
  <General>
    <Name Prefix="MR" First="Mickey" Middle="M" Last="Mouse" Suffix="I" Title="BA" Gender="M" BirthMonth="02" BirthDay="26" BirthYear="1984"/>
    <Email Work="test9999@acme.com" Home="Homeemail@gmail.com"/>
    <EmployeeId>9948228</EmployeeId>
  </General>
  <ConfigProperties>
    <LoginID>root/General/EmployeeId</LoginID>
  </ConfigProperties>
</root>

XSL 示例:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" encoding="utf-8" indent="yes" />
<xsl:template match="/">
  <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <xsl:variable name="xxLI" select="root/ConfigProperties/LoginID" />
    <xsl:attribute name="LoginId"><xsl:value-of select="$xxLI"/></xsl:attribute>
  </Response>
</xsl:template>
</xsl:stylesheet>

已转换 XML:

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          LoginId="root/General/EmployeeId"/>

我真正希望得到的是:

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          LoginId="9948228"/>

我被难住了。有什么想法吗?

在普通 XSLT 1 中无法做到这一点,但如果您的 XSLT 处理器支持 "dynamic" 扩展(XALAN 支持它),您可以这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:dyn="http://exslt.org/dynamic"
    extension-element-prefixes="dyn">

    <xsl:output method="xml" omit-xml-declaration="no" encoding="utf-8" indent="yes" />
    <xsl:template match="/">
        <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <xsl:variable name="xxLI" select="root/ConfigProperties/LoginID" />
            <xsl:attribute name="LoginId"><xsl:value-of select="dyn:evaluate($xxLI)"/></xsl:attribute>
        </Response>
    </xsl:template>
</xsl:stylesheet>

我在 Oxygen/XML 中使用 XALAN 对此进行了测试并获得了此输出

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" LoginId="9948228"/>

谢谢 - 在花了几个小时在 libxslt 中正确实施后,工作起来非常顺利。对于任何有兴趣使用 c 的人,请声明以下内容:

#include <libexslt/exslt.h>
#include <libexslt/exsltconfig.h>

然后在您的代码中包含以下行:

exsltRegisterAll();

并确保在编译时引用该库

-lexslt