XSLT を用いて XML の属性名をもとにノード名を付け替える

April 10, 2007

マッピングが定義されたXMLを使って、itemノードのname属性値から対応するタグ名に変換する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8"/>
<xsl:variable name="convtable" select="document('mapping.xml')"/>
<xsl:template match="/records">
<xsl:copy>
<xsl:apply-templates select="record"/>
</xsl:copy>
</xsl:template>
<xsl:template match="record">
<xsl:copy>
<xsl:apply-templates select="item"/>
</xsl:copy>
</xsl:template>
<xsl:template match="item">
<xsl:variable name="oldname" select="@name"/>
<xsl:variable name="newname" select="$convtable/mapping/item\[@from=$oldname\]/@to"/>
<xsl:choose>
<xsl:when test="$newname">
<xsl:element name="{$newname}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

mapping.xml

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<mapping>
<item from="タイトル" to="title"/>
<item from="著者名" to="author"/>
</mapping>

入力

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<records>
<record>
<item name="タイトル">はてな</item>
<item name="著者名">スタッフ</item>
</record>
<record>
<item name="タイトル">小説</item>
<item name="著者名">誰かさん</item>
</record>
</records>

結果

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<records>
<record>
<title>はてな</title>
<author>スタッフ</author>
</record>
<record>
<title>小説</title>
<author>誰かさん</author>
</record>
</records>
XSLT

tilfin freelance software engineer