问题描述:

How can i concat the three elements name, age and country to one line?

<?xml version="1.0" encoding="utf-8"?>

<Person>

<Student>

<Name>James</Name>

<Age>21</Age>

<Country>Australia </Country>

</Student>

</Person>

so i can get the element values to one line.

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

网友答案:

Simple just do this;

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>

Just added the extra text you could remove it or have ' ' (it blank) so you get spaces.

Output:

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

With spaces;

<?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>

Output:

<?xml version="1.0" encoding="UTF-8"?>
  <Info>James 21 Australia </Info>
网友答案:

You could use 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>

However there won't be any spaces separating your values:

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

Instead you could use xsl:apply-templates and match each child of Student and output a space when necessary...

<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>

Output...

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

If you were using XSLT 2.0, you could use the separator attribute on xsl:value-of...

<xsl:template match="Student">
    <info><xsl:value-of select="*" separator=" "/></info>
</xsl:template>
相关阅读:
Top