xml - xslt 测试属性是否存在

标签 xml xslt

我有以下 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>

https://gist.github.com/guinslym/5ce47460a31fe4c4046b

最佳答案

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/

相关文章:

sql - 如何在 SQL Server 2008 中增加 XML 数据类型

java - 检测到 Android Studio 项目

android - android中的固定元素?

java - 网站中的 XML 解析

xslt - 如何在visual studio环境中使用EXSLT

php - 使用 php 将 xml 转换为 html

java - 如何为给定 xml 的客户端 saaj 创建 SOAP 请求

javascript - 生成要应用于 XML 文件的 XSL

xslt - 排除 XML 结果中的命名空间

html - XSLT 抽象