xml - 如何使用 xslt 删除最外层的包装?

标签 xml xslt

示例 xml 是:

<a amp="a"><b><c>this is the text</c></b></a>

需要转换为:

<a amp="a"><c>this is the text</c></a>

最佳答案

解决方案#1:smaccoun 解决方案的轻微改进,将保留 c 上的所有属性。元素(对于 XML 来说不是必需的):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="c">
        <xsl:copy-of select="." />
    </xsl:template>
</xsl:stylesheet>

解决方案 #2 另一种利用 built-in template rules 的替代方案,为所有元素应用模板并复制所有 text() :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template for the c element, it's decendant nodes, 
        and attributes (which will only get applied from c or 
        descendant elements)-->
    <xsl:template match="@*|c//node()|c">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

解决方案#3:修改后的 identity transform:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template, copies all content by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--don't generate content for these matched elements, 
        just apply-templates to it's children-->
    <xsl:template match="a|b">
        <xsl:apply-templates/>
    </xsl:template>     
</xsl:stylesheet>

解决方案#4如果您知道自己想要什么,只需从根节点上的匹配中复制它即可

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:copy-of select="a/b/c" />
    </xsl:template>
</xsl:stylesheet>

如果您想简单地删除 <b>元素,那么修改后的身份转换应与匹配 <b> 的模板一起使用简单地将模板应用于其子元素的元素。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--identity template, copies all content by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--don't generate content for the <b>, just apply-templates to it's children-->
    <xsl:template match="b">
        <xsl:apply-templates/>
    </xsl:template>     
</xsl:stylesheet>

关于xml - 如何使用 xslt 删除最外层的包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616348/

相关文章:

xml - 使用 xsl 从 xml 中删除 xmlns 命名空间

java - 我需要一个简单的命令行程序来使用 XSL 样式表转换 XML

xml - 根据 WSDL(xsd 架构)验证 xml 时了解 elementFormDefault 合格/不合格

c++ - boost::archive::xml_iarchive 因 xml(反序列化上下文)而失败

python - 根据属性值使用 lxml 对子元素进行排序

java - 在 RecyclerView 项目之间设置自定义分隔线

xslt - 如何使用 XSLT 从 XSD 生成简单文档

xml - 如何xsl最后用空值升序排序

xml - XSLT - 识别节点后跟另一个节点

php - 构建自定义API——需要逻辑检查