【发布时间】:2011-06-05 12:38:45
【问题描述】:
我有以下一组文件:
SourceFile.xml:
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee id="1">
<firstname relationship="headnote">Atif</firstname>
<lastname relationship="lname">Bashir</lastname>
<age relationship="age">32</age>
</Employee>
</Employees>
参数设置.xml
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Employee id="1">
<sourceFile>Lookup1.xml</sourceFile>
<sourceXpathfield>Employees/Employee[@id</sourceXpathfield>
<lookupXpathfield>Employees/Employee[@id='1']</lookupXpathfield>
<elementstoinsert>xyz</elementstoinsert>
</Employee>
</Settings>
查找.xml
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee id="1">
<department code="102">HR</department>
</Employee>
</Employees>
transform.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:include href="identity.xsl"/>
<xsl:param name="EmployeeId" select="'1,2'" />
<xsl:variable name="FileSettings" select="document('test3.xml')" />
<xsl:variable name="SuppressSetting" select="$FileSettings/Settings/Employee[@id = tokenize($EmployeeId, ',')]" />
<xsl:template match="Employee">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="publisher" />
<xsl:apply-templates select="node() except publisher"/>
<xsl:variable name="outerfile" select="document($SuppressSetting/sourceFile)"></xsl:variable>
<xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>
<xsl:value-of select="$outerfiledetails"></xsl:value-of>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出应该是:
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee id="1">
<firstname relationship="headnote">Atif</firstname>
<lastname relationship="lname">Bashir</lastname>
<age relationship="age">32</age>
HR
</Employee>
</Employees>
我在 Transform.xsl 中更改了以下行
<xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>
进入
<xsl:variable name="outerfiledetails" select="$outerfile/Employees/Employee[@id='1']"></xsl:variable>
然后我得到我的输出,但我想将 SourceFile.xml 和 Lookup.xml 的 XPath 压缩保留到 ParamerterSettings.xml 中,以便我可以编写更通用的脚本。除了动态 xpath 之外,这可以通过任何其他方式完成吗?任何想法或暗示都将受到高度赞赏。
【问题讨论】:
-
你已经简化了你最初的几乎可怕的问题,这是一个很好的进步,但是这个问题仍然太复杂并且没有明确定义。尝试改写它并进一步简化它——我相信你不需要所有的细节。特别是,必须处理两个以上的文件,这让每个人都放弃了,甚至试图理解这个问题。太复杂了:我永远不会以这种方式设计 XSLT 应用程序,相信我,我的 XSLT 应用程序具有真正具有挑战性的复杂性,99% 的开发人员认为使用 XSLT 是不可能的。
-
嗨 Dimitre,我想要的是从外部文件执行 xpath 值。原因是我有多个外部文件,我想从中获取数据并将该数据插入主源文件。我可以通过硬编码多个模板来做到这一点,但我想避免这种情况,并制作一个模板,该模板根据不同的连接或 xpath 值从多个文件中读取定义为外部文件中的设置。
-
@Nick-Jones 的回答是正确的:这不能在 XSLT/XPath 2.0 中完成,它可能由下一个版本提供。然而,我高度怀疑动态 XPath 评估的必要性——如果你很好地描述了你的问题,那么可能有一个不需要这个的解决方案。为什么不以最简单的形式问这个问题:“我如何评估这个 XML 文档中包含的这个表达式?”。虽然不可能使用纯 XSLT 解决方案,但我知道至少有三种不同的“混合”解决方案可以解决这个问题。
-
查看我的回答,了解您的问题的三种不同解决方案,这样您就不必等到 XSLT 3.0 到来。 :)