<EmployeeDetails>
<Employee>
<Name>TEST</Name>
</Employee>
<Employee>
<Name>TEST</Name>
</Employee>
<Employee>
<Name>TEST</Name>
</Employee>
<Employee>
<Name>TEST</Name>
</Employee>
<Employee>
<Name>TEST</Name>
</Employee>
</EmployeeDetails>
Run Code Online (Sandbox Code Playgroud)
我尝试使用xslt如下:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl"
exclude-result-prefixes="xd"
version="1.0">
<xsl:template match="EmployeeDetails/Employee">
<xsl:copy>
<xsl:attribute name="id"><xsl:value-of select="position()"/></xsl:attribute>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
对于上面的xslt,position()的输出打印为2,4,6,8,10.
输出应该是:
<EmployeeDetails>
<Employee id="1">
<Name>TEST</Name>
</Employee>
<Employee id="2">
<Name>TEST</Name>
</Employee>
<Employee id="3">
<Name>TEST</Name>
</Employee>
<Employee id="4">
<Name>TEST</Name>
</Employee>
<Employee id="5">
<Name>TEST</Name>
</Employee>
</EmployeeDetails>
Run Code Online (Sandbox Code Playgroud)
如何打印像1,2,3 ....的序列作为id属性.
小智 27
该xsl:number指令恰好是为了完成这项任务:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Employee">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="id">
<xsl:number/>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输出:
<EmployeeDetails>
<Employee id="1">
<Name>TEST</Name>
</Employee>
<Employee id="2">
<Name>TEST</Name>
</Employee>
<Employee id="3">
<Name>TEST</Name>
</Employee>
<Employee id="4">
<Name>TEST</Name>
</Employee>
<Employee id="5">
<Name>TEST</Name>
</Employee>
</EmployeeDetails>
Run Code Online (Sandbox Code Playgroud)
在你第一次之前<xsl:template>,添加
<xsl:strip-space elements="*"/>
Run Code Online (Sandbox Code Playgroud)
这将消除@khachik所指的仅空白文本节点.那么你的位置数应该是你所期望的.
| 归档时间: |
|
| 查看次数: |
84857 次 |
| 最近记录: |