【问题标题】:XSL transform grandchild node values to element attribute valueXSL 将孙节点值转换为元素属性值
【发布时间】:2015-09-30 10:24:19
【问题描述】:

给定以下 XML:

<test id="s1-t2" name="Lorem ipsum">
    ...
    <tags>
        <tag>foo</tag>
        <tag>bar</tag>
    </tags>
    ...
</test>

我想在测试元素的名称属性中附加每个标签元素的节点值。所以生成的 XML 应该是这样的:

<test id="s1-t2" name="Lorem ipsum [foo][bar]">
    ...
    <tags>
        <tag>foo</tag>
        <tag>bar</tag>
    </tags>
    ...
</test>

标签元素(及其内容)可以保留在原地,但这不是必需的。

到目前为止,我已经尝试过这样的事情:

<xsl:template match="test">
    <test>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="name">
            <xsl:value-of select="tags/tag"/>
        </xsl:attribute>
        <xsl:apply-templates select="node()"/>
    </test>
</xsl:template>

但这不起作用。即使它可以工作,它也会替换 name 属性并且只用一个标签。距离我上次写任何 XSLT 已经太久了。

【问题讨论】:

  • 您使用的 XSLT 版本是什么? 1.0 还是 2.0?

标签: xml xslt


【解决方案1】:

我想在名称中附加每个标签元素的节点值 测试元素的属性。

试试这个方法:

XSLT 1.0

<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:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/test/@name">
    <xsl:attribute name="name">
        <xsl:value-of select="."/>
        <xsl:for-each select="../tags/tag">
            <xsl:text>[</xsl:text>
            <xsl:value-of select="."/>
            <xsl:text>]</xsl:text>
        </xsl:for-each>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多