サンプルコード
変換させるxmlファイル
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="sample.xsl"?>
<root>
<employee>
<name>田中</name>
<department>営業</department>
</employee>
<employee>
<name>鈴木</name>
<department>営業</department>
</employee>
</root>
変換後のxmlファイル
こちらをXSLのサンプルを見ずに作成できるようになるよう練習するとよい。
<?xml version="1.0" encoding="UTF-8"?> <ルート> <部署>営業</部署> <社員> <名前>田中</名前> </社員> <社員> <名前>鈴木</名前> </社員> </ルート>
適用したxslファイル
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="root"/>
</xsl:template>
<xsl:template match="root">
<ルート>
<部署>営業</部署>
<xsl:for-each select="employee">
<社員>
<名前><xsl:value-of select="name"></xsl:value-of></名前>
</社員>
</xsl:for-each>
</ルート>
</xsl:template>
</xsl:stylesheet>
解説
変換させるxmlファイル
<?xml-stylesheet type="text/xsl" href="sample.xsl"?>
元のxmlには、xslファイルを適用するために、
上記の通りに設定する必要がある。
href属性にファイルパスを入れます。
適用したxslファイル
<xsl:template match="/">
<xsl:apply-templates select="root"/>
</xsl:template>
この文で、別のところで宣言したrootの内容を呼び出している。
呼び出して、forやxmlのデータを呼び出して、タグ名など変えて新しく作り直している。
