我试图在子节点的值等于某个字符串时,向该节点添加属性。
我有一个名为 main.xml 的文件。
<Employees>
<Employee>
<countryid>32</countryid>
<id name="id">1</id>
<firstname >ABC</firstname>
<lastname >XYZ</lastname>
</Employee>
<Employee>
<countryid>100</countryid>
<id name="id">2</id>
<firstname >ddd</firstname>
<lastname >ggg</lastname>
</Employee>
</Employees>
假设国家ID等于32,则应该在Employee节点中添加属性country=32。输出结果应如下所示:
output.xml
<Employees>
<Employee countryid="32">
<countryid>32</countryid>
<id name="id">1</id>
<firstname >ABC</firstname>
<lastname >XYZ</lastname>
</Employee>
<Employee>
<countryid>100</countryid>
<id name="id">2</id>
<firstname >ddd</firstname>
<lastname >ggg</lastname>
</Employee>
</Employees>
我正在使用以下脚本,但是出现了错误:无法在包含元素的子元素之后创建属性节点:
Transform.xsl
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="Employees/Employee/countryid[.=32']">
<xsl:attribute name="countryid">32</xsl:attribute>
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
非常感谢任何帮助。我还想知道我们是否可以将countryid作为逗号分隔的值传递,这样我就可以传递32、100,然后它应该将属性添加到所有匹配的节点。
谢谢。