我需要一些有关我要构建的XSLT代码的帮助。以下XML代码具有多个子节点,我需要将其转换为“ variable” _(文件名值)的串联值。我的示例XML在下面,
<Attachments>
<AttachFile>
<FilContentType>application/pdf; name=docxyz1.pdf</FilContentType>
<FileName>docxyz1.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf;name=docxyz2.pdf</FilContentType>
<FileName>docxyz2.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf; name=docxyz3.pdf</FilContentType>
<FileName>docxyz3.pdf.pdf</FileName>
</AttachFile>
</Attachments>
转换后的输出必须如下
<Attachments>
<AttachFile>
<FilContentType>application/pdf; name=docxyz1.pdf</FilContentType>
<FileName>1_docxyz1.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf;name=docxyz2.pdf</FilContentType>
<FileName>2_docxyz2.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf; name=docxyz3.pdf</FilContentType>
<FileName>3_docxyz3.pdf.pdf</FileName>
</AttachFile>
</Attachments>
我尝试调用模板并使用for-each,但是我的逻辑不正确。我的XSLT代码如下:
<xsl:variable name="Count" select="count(/Attachments/AttachFile/FileName)"/>
<xsl:variable name="i" select="1"></xsl:variable>
<xsl:template match="/">
<xsl:apply-templates select="Attachments"/>
</xsl:template>
<xsl:template match="Attachments">
<Attachments>
<xsl:for-each select="./Attachments/AttachFile">
<AttachFile>
<FilContentType><xsl:value-of select="FilContentType"/></FilContentType>
<xsl:call-template name="Increment">
<xsl:with-param name="i" select="1"/>
<xsl:with-param name="Count" select="$Count"/>
</xsl:call-template>
</AttachFile>
</xsl:for-each>
</Attachments>
</xsl:template>
<xsl:template name="Increment">
<xsl:param name="i"/>
<xsl:param name="Count"/>
<xsl:if test="$Count > $i">
<Filename>
<xsl:value-of select="concat($i,'_',FileName)"/>
</Filename>
<xsl:call-template name="Increment">
<xsl:with-param name="i" select="$i + 1"/>
<xsl:with-param name="Count" select="$Count"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
谢谢
答案 0 :(得分:2)
不是很简单吗?
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:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="FileName">
<xsl:copy>
<xsl:number count="AttachFile" format="1_"/>
<xsl:value-of select="." />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
应用于您的示例,结果将是:
结果
<?xml version="1.0" encoding="utf-16"?>
<Attachments>
<AttachFile>
<FilContentType>application/pdf; name=docxyz1.pdf</FilContentType>
<FileName>1_docxyz1.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf;name=docxyz2.pdf</FilContentType>
<FileName>2_docxyz2.pdf</FileName>
</AttachFile>
<AttachFile>
<FilContentType>application/pdf; name=docxyz3.pdf</FilContentType>
<FileName>3_docxyz3.pdf.pdf</FileName>
</AttachFile>
</Attachments>