这是一个简化版本的输入XML:
<?xml version="1.0" encoding="UTF-8"?>
<Project>
<RessourcePool>
<Stock Ref="Ref_1" Name="135gl" Weight="135" WeightUnit="gsm"/>
<Stock Ref="Ref_2" Name="300ma" Weight="300" WeightUnit="gsm"/>
</RessourcePool>
<Product Type="Bound">
<StockRef rRef="Ref_1"/>
</Product>
<Product Type="Unbound">
<StockRef rRef="Ref_2"/>
</Product>
</Project>
基本上,我开始了一个遍历product并将它们转换为新格式的XSL,因为在Input中有一个交叉引用,所以我不知道如何将其放入if case中,或者是否有更好的解决方案。开始的XSL看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="//Product">
<xsl:variable name="elem-name">
<xsl:choose>
<xsl:when test='@Type="Bound"'>BoundComponent</xsl:when>
<xsl:otherwise>UnboundComponent</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:element name="{$elem-name}">
<!-- Now i want to add an attribute inside the element which is called "Material", therefore i want to check if the StockRef of the Product matches with one of the Stocks in the RessourcePool, if so it should take the @Name @Weight and @WeightUnit of the matching Stock and put it inside the Material Attribute like Material="135gl, 135gsm"-->
</xsl:element>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
我猜你想做这样的事情:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="stk" match="Stock" use="@Ref" />
<xsl:template match="/Project">
<root>
<xsl:for-each select="Product">
<xsl:variable name="elem-name">
<xsl:choose>
<xsl:when test="@Type='Bound'">BoundComponent</xsl:when>
<xsl:otherwise>UnboundComponent</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:element name="{$elem-name}">
<xsl:variable name="stock" select="key('stk', StockRef/@rRef)" />
<xsl:attribute name="Material">
<xsl:value-of select="$stock/@Name"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="$stock/@Weight"/>
<xsl:value-of select="$stock/@WeightUnit"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>
应用到你的输入示例,这将产生:
结果
<?xml version="1.0" encoding="UTF-8"?>
<root>
<BoundComponent Material="135gl, 135gsm"/>
<UnboundComponent Material="300ma, 300gsm"/>
</root>
注意,这里假设最多有一个Stock
具有引用的Ref
值。