首页 > 解决方案 > 如何将一个字符串中的 2 个 xml 元素与 XSLT 结合起来?

问题描述

我的 XML 文件中有两个元素,我想在一个字符串中组合 2 个值。这是我的 XSLT 解决方案:

 <xsl:for-each select="housenumber/@value | housenumberletter/@value">
 <houseinformation>
 <xsl:variable name="info" select="xs:string((housenumber| housenumberletter)/@value)" />
 <valueString value="info"/>
 </houseinformation>
 </xsl:for-each>

这是我在氧气中测试时的结果:

<houseinformation>
<valueString value="info"/>
</houseinformation>
<houseinformation>
<valueString value="info"/>
</houseinformation>

我想要的预期结果是这样的:

<houseinformation>
<valueString value="4A"/>
</houseinformation>

我也尝试了concat功能,但它没有用。

如何将 XML 中的两个元素组合在一个字符串中?

更新:

我的 xml 文件:

<xml>   
    <data>  
    <housenumber value="15"/>
    <houseletter value="A"/> 
    </data>
</xml> 

标签: xmlxslt

解决方案


给定您的 XML 示例,以下样式表:

XSLT 2.0

<xsl:stylesheet version="2.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="/xml">
    <root>
        <xsl:for-each select="data">
            <xsl:variable name="info" select="(housenumber | houseletter)/@value" />
            <houseinformation>
                <valueString value="{$info}"/>
            </houseinformation>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

将返回:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <houseinformation>
      <valueString value="15 A"/>
   </houseinformation>
</root>

如果您不想要空格分隔符,请尝试:

<xsl:stylesheet version="2.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="/xml">
    <root>
        <xsl:for-each select="data">
            <xsl:variable name="info" select="(housenumber | houseletter)/@value" />
            <houseinformation>
                <valueString>
                      <xsl:attribute name="value" select="$info" separator=""/>
                </valueString>
            </houseinformation>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

或者简单地说:

<xsl:stylesheet version="2.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="/xml">
    <root>
        <xsl:for-each select="data">
            <houseinformation>
                <valueString value="{concat(housenumber/@value, houseletter/@value)}"/>
            </houseinformation>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

推荐阅读