我有以下 xslt。我注意到有时元素名称“tuple”有一个属性。我想删除属性并将其添加为元素。我添加了测试 来验证“tuple”是否具有属性,但它返回一个空白的“ecatalogue”元素。
<?xml version="1.0" encoding="UTF-8"?>
<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:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="atom">
<xsl:element name="{@name}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="table">
<xsl:element name="{@name}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<!--this test doesn't work properly -->
<xsl:template match="tuple">
<xsl:choose>
<xsl:when test="@name">
<xsl:apply-templates />
</xsl:when>
<xsl:otherwise>
<!-- nothing to do
the node should stay the same
-->
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- end test -->
</xsl:stylesheet>
我使用上面的模板得到的结果。
<ecatalogue>
</ecatalogue>
最佳答案
I notice that sometimes the element name 'tuple' has an attribute. I want to remove the attribute and add it as an Element. I added a test to verify if 'tuple' has an attribute
这绝对不是使用 XSLT 的最佳方法。您想要转换属性,而不是其父 tuple
元素 - 因此您的模板应该直接匹配属性,例如:
<xsl:template match="tuple/@*">
<xsl:element name="{name()}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
这里不需要测试:如果属性存在,模板会匹配并处理;否则,根本不会应用该模板。
--
注意:以上假设您要将属性转换为 tuple
的子元素,与另一个已经存在的子元素同级。您的帖子在这一点上不是很清楚。
关于xml - xslt 测试属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388832/