尝试这样的事情:
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="def_InvoicePeriod" select="'1'" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="InvoicePeriod" >
<invoiceP>
<xsl:value-of select="."/>
</invoiceP>
</xsl:template>
<xsl:template match="Transaction[not(InvoicePeriod)]" >
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<invoiceP>
<xsl:value-of select="$def_InvoicePeriod"/>
</invoiceP>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
def_InvoicePeriod 可以在调用转换时更改。例如使用 xslptorc:
xsltproc --stringparam def_InvoicePeriod 2 xsltfile xmlfile
更新:(似乎 invoiceP 应该是 Transaction 中的一个属性,默认值也应该用于空值或 value="0"。
尝试这个:
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="def_InvoicePeriod" select="'1'" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="InvoicePeriod" />
<xsl:template match="Transaction" >
<xsl:copy>
<xsl:attribute name="invoiceP">
<xsl:choose>
<xsl:when test="number(InvoicePeriod) > '0' ">
<xsl:value-of select="InvoicePeriod"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$def_InvoicePeriod"/>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
更新测试输入:
<?xml version="1.0"?>
<xml>
<Transaction>
<InvoicePeriod>1</InvoicePeriod>
<Product>Shoe</Product>
</Transaction>
<Transaction>
<InvoicePeriod>3</InvoicePeriod>
<Product>Shoe1</Product>
</Transaction>
<Transaction>
<InvoicePeriod>0</InvoicePeriod>
<Product>Shoe2</Product>
</Transaction>
<Transaction>
<Product>Shoe3</Product>
</Transaction>
</xml>
输出:
<?xml version="1.0"?>
<xnl>
<Transaction invoiceP="1">
<Product>Shoe</Product>
</Transaction>
<Transaction invoiceP="3">
<Product>Shoe1</Product>
</Transaction>
<Transaction invoiceP="1">
<Product>Shoe2</Product>
</Transaction>
<Transaction invoiceP="1">
<Product>Shoe3</Product>
</Transaction>
</xnl>