輸入:
<?xml version="1.0" encoding="UTF-8"?>
<Project ID="123">
<ProductPool>
<Product Type="A" ID="123" DueDate="123" Name="ABC"/>
<Product Type="B" ID="123" DueDate="123" Name="ABC"/>
<Product Type="A" ID="123" DueDate="123" Name="ABC"/>
<Product Type="B" ID="123" DueDate="123" Name="ABC"/>
<Product Type="A" ID="123" DueDate="123" Name="ABC"/>
</ProductPool>
</Project>
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:element name="Product">
<xsl:attribute name="ID">
<xsl:value-of select="//Project/@ID"/>
</xsl:attribute>
<xsl:variable name="elem-name">
<xsl:choose>
<xsl:when test='//Product[@Type="A"]'>BoundComponent</xsl:when>
<xsl:otherwise>UnboundComponent</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:for-each select="//Product">
<xsl:element name="{$elem-name}">
<xsl:attribute name="ID">
<xsl:value-of select="@Name"/>
</xsl:attribute>
<xsl:attribute name="DueDate">
<xsl:value-of select="@DueDate"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
輸出:
<?xml version="1.0"?>
<Product ID="123">
<BoundComponent ID="ABC" Duedate="123"/>
<BoundComponent ID="ABC" Duedate="123"/>
<BoundComponent ID="ABC" Duedate="123"/>
<BoundComponent ID="ABC" Duedate="123"/>
<BoundComponent ID="ABC" Duedate="123"/>
</Product>
出于某種原因,一旦在整個輸入中找到一個 Type="A",所有元素都稱為 BoundComponent,但我的目標是分離輸出,因此找到的每個產品都將是一個稱為 Bound 或 Unbound 的元素,具體取決于關于它在輸入中的型別,我不知道為什么會這樣,因為它已經是一個 for-each 回圈。有任何想法嗎?
uj5u.com熱心網友回復:
您的$elem-name變數被系結到回圈外的值。如果將xsl:variable回圈放在內部,它將被系結到每個 distinct 的適當值Product。IE
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:element name="Product">
<xsl:attribute name="ID">
<xsl:value-of select="//Project/@ID"/>
</xsl:attribute>
<xsl:for-each select="//Product">
<xsl:variable name="elem-name">
<xsl:choose>
<xsl:when test='@Type="A"'>BoundComponent</xsl:when>
<xsl:otherwise>UnboundComponent</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:element name="{$elem-name}">
<xsl:attribute name="ID">
<xsl:value-of select="@Name"/>
</xsl:attribute>
<xsl:attribute name="DueDate">
<xsl:value-of select="@DueDate"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489242.html
