Reputation: 45
I'm struggling with an XML file in which I need to add some curly braces. I'm already using XSLT (1.0) to generate the XML file. The only characters that are missing are the { } around a value in the XML file.
The source file looks like
<?xml version='1.0' encoding='utf-8'?>
<container>
<pan>
<id>1</id>
<input>
<url>thisfile-1.xml</url>
</input>
<output>
<url>thisoutput-1.txt</url>
</output>
</pan>
<pan>
<id>2</id>
<input>
<url>anotherfile-2.xml</url>
</input>
<output>
<url>oldoutput-2.txt</url>
</output>
</pan>
<pan>
<id>3</id>
<input>
<url>alsofile-3.xml</url>
</input>
<output>
<url>newoutput-3.txt</url>
</output>
</pan>
</container>
The variable I need to change is in container/pan/input/url The resulting file should look like
<?xml version='1.0' encoding='utf-8'?>
<container>
<pan>
<id>1</id>
<input>
<url>{thisfile-1.xml}</url>
</input>
<output>
<url>thisoutput-1.txt</url>
</output>
</pan>
<pan>
<id>2</id>
<input>
<url>{anotherfile-2.xml}</url>
</input>
<output>
<url>oldoutput-2.txt</url>
</output>
</pan>
<pan>
<id>3</id>
<input>
<url>{alsofile-3.xml}</url>
</input>
<output>
<url>newoutput-3.txt</url>
</output>
</pan>
</container>
The url's are variable and only the input url should be changed not the output url.
I tried some string replacement examples but they are actually replacing the content, I want to preserve the content and adding the braces only. Any ideas would be appreciated, I'm on a dead end right now.
The XSLT I'm using now is
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="input/url/text()">
<xsl:text>replacetext</xsl:text>
</xsl:template>
</xsl:stylesheet>
This only replaces the input url .... This is as far as my knowledge about XSLT goes.
Upvotes: 4
Views: 976
Reputation: 111561
You have everything set up well. Just change
<xsl:text>replacetext</xsl:text>
to
<xsl:value-of select="concat('{', ., '}')"/>
to wrap the existing input/url
text (.
) with {
and }
as requested.
Here's the full XSLT, which you wisely based on the identity transformation, plus the above fix:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="input/url/text()">
<xsl:value-of select="concat('{', ., '}')"/>
</xsl:template>
</xsl:stylesheet>
Upvotes: 3