サンプルコード
変換させるxmlファイル
1 2 3 4 5 6 7 8 9 10 11 12 |
<?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のサンプルを見ずに作成できるようになるよう練習するとよい。
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="UTF-8"?> <ルート> <部署>営業</部署> <社員> <名前>田中</名前> </社員> <社員> <名前>鈴木</名前> </社員> </ルート> |
適用したxslファイル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?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ファイル
1 |
<?xml-stylesheet type="text/xsl" href="sample.xsl"?> |
元のxmlには、xslファイルを適用するために、
上記の通りに設定する必要がある。
href属性にファイルパスを入れます。
適用したxslファイル
1 2 3 |
<xsl:template match="/"> <xsl:apply-templates select="root"/> </xsl:template> |
呼び出して、forやxmlのデータを呼び出して、タグ名など変えて新しく作り直している。