【问题标题】:XSLT merge nodes attributes to one attributeXSLT 将节点属性合并为一个属性
【发布时间】:2021-06-17 23:10:04
【问题描述】:

我有这个 xml 输入,需要将其转换为另一个 xml(svg 文件),将多个节点属性合并为一个属性。

xsl 有什么解决办法吗?

<b>
    <h a="1" b="2" c="3"/>
    <h a="4" b="5" c="6"/>
    <h a="7" b="8" c="9"/>
</b>

预期输出:

<g>
    <p d="1,2,3   4,5,6   7,8,9"/>
</g>

所以试图与一个 xsl 合并(实际上是几个......),但我找不到窍门......

这是我最后一次尝试,只输出最后一个元素 (7,8,9)。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/b">
        <g>
            <p>
                <xsl:apply-templates select="h"/>
            </p>
        </g>
    </xsl:template>
    <xsl:template match="h">
        <xsl:attribute name="p">
            <xsl:value-of select="concat(@a,' ',@b,' ',@c)"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

这个 xsl 的输出:

<?xml version="1.0" encoding="UTF-8"?><g><p p="4 5 6"/></g>

谢谢

【问题讨论】:

  • d="1,2,3 4,5,6 7,8,9" 你确定要在组之间除了空格之外没有分隔符吗?
  • 请注意 &lt;p&gt; 元素在 SVG &lt;g&gt; 内无效。如果那是,事实上,你正在尝试做的事情。

标签: xml svg xslt


【解决方案1】:

实现此目的的一种方法(对 XSLT-1.0 代码进行最少修改)是:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <g>
            <xsl:apply-templates select="b"/>
        </g>
    </xsl:template>
    
    <xsl:template match="b">
        <p>
            <xsl:attribute name="d">
                <xsl:for-each select="h">
                    <xsl:value-of select="concat(@a,',',@b,',',@c)"/>
                    <xsl:if test="position()!=last()"><xsl:text>   </xsl:text></xsl:if>
                </xsl:for-each>
            </xsl:attribute>
        </p>
    </xsl:template>
</xsl:stylesheet>

输出如预期:

<?xml version="1.0"?>
<g><p d="1,2,3   4,5,6   7,8,9"/></g>

【讨论】:

  • 谢谢!所以在属性定义中循环。聪明!
  • 很高兴能为您提供帮助。通过点击左侧的绿色箭头来接受我的回答会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多