Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

xml - how to fill text templates using xslt

I have an XML file with information, for example:

<letter>
  <name>Test</name>
  <age>20</age>
  <me>Me</me>
</letter>

And then I have an text template like:

Dear $name,

some text with other variables like $age or $name again

greatings $me

When using xslt to transform the XML to the plain text letter I can use something like:

<xsl:text>Dear </xsl:text><xsl:value-of select="name"/><xsl:text>

some text with other variables like </xsl:text>
<xsl:value-of select="age"/><xsl:text> or </xsl:text>
<xsl:value-of select="name"/><xsl:text> again

greatings </xsl:text><xsl:value-of select="me"/>

But when I get more and more variables and more text this becomes a nightmare to enter and to maintain.

Is there some way to do this in a cleaner way using xslt? I would prefer if I could just use the text template I used as an example above and have $name and $age replaced with the correct values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This stylesheet:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:my="my">
    <xsl:output method="text"/>
    <xsl:preserve-space elements="my:layout"/>
    <my:layout>Dear <name/>,

some text with other variables like <age/> or <name/> again

greatings <me/></my:layout>
    <xsl:variable name="vData" select="/"/>
    <xsl:template match="/">
        <xsl:apply-templates select="document('')/*/my:layout/node()"/>
    </xsl:template>
    <xsl:template match="*/*">
        <xsl:value-of select="$vData//*[name()=name(current())]"/>
    </xsl:template>
</xsl:stylesheet>

Output:

Dear Test,

some text with other variables like 20 or Test again

greatings Me

Note: For more complex population pattern (i.e. iteration), check this posts: Sitemesh like functionality with XSLT? and XSLT Layouts With Dynamic Content Region


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...