Concat元素值为一行

时间:2013-11-26 03:34:33

标签: xml xslt xslt-1.0

如何将三个元素的名称,年龄和国家连接到一行?

<?xml version="1.0" encoding="utf-8"?>
 <Person>
  <Student>
   <Name>James</Name>
   <Age>21</Age>
   <Country>Australia </Country>
  </Student>
 </Person>

所以我可以将元素值放到一行。

<info> ....... <info>

2 个答案:

答案 0 :(得分:1)

简单就是这样做;

<强> XSL:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Student">
<xsl:element name = "Info">
        <xsl:value-of select="concat(Name,' is ',Age,' born in ',Country)"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

刚刚添加了可以删除它的额外文本或者''(它为空白),这样就可以获得空格。

<强>输出:

<?xml version="1.0" encoding="UTF-8"?>
  <Info>James is 21 born in Australia </Info>

有空格;

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Student">
<xsl:element name = "Info">
        <xsl:value-of select="concat(Name,' ',Age,' ',Country)"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

<强>输出:

<?xml version="1.0" encoding="UTF-8"?>
  <Info>James 21 Australia </Info>

答案 1 :(得分:0)

您可以使用xsl:value-of ...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="Student">
        <info><xsl:value-of select="."/></info>
    </xsl:template>

</xsl:stylesheet>

但是,您的值之间不会有任何空格:

<Person>
   <info>James21Australia </info>
</Person>

相反,您可以使用xsl:apply-templates并匹配Student的每个子项,并在必要时输出空格...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="Student">
        <info><xsl:apply-templates/></info>
    </xsl:template>

    <xsl:template match="Student/*">
        <xsl:if test="not(position()=1)">
            <xsl:text> </xsl:text>
        </xsl:if>
        <xsl:value-of select="."/>
    </xsl:template>

</xsl:stylesheet>

...输出

<Person>
   <info>James 21 Australia </info>
</Person>

如果您使用的是XSLT 2.0,则可以使用separator上的xsl:value-of属性...

<xsl:template match="Student">
    <info><xsl:value-of select="*" separator=" "/></info>
</xsl:template>
相关问题