XSLT を用いて XML の属性名をもとにノード名を付け替える
マッピングが定義されたXMLを使って、itemノードのname属性値から対応するタグ名に変換する。
<?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
<?xml version="1.0" encoding="utf-8"?> <mapping> <item from="タイトル" to="title"/> <item from="著者名" to="author"/> </mapping>
入力
<?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>
結果
<?xml version="1.0" encoding="utf-8"?> <records> <record> <title>はてな</title> <author>スタッフ</author> </record> <record> <title>小説</title> <author>誰かさん</author> </record> </records>