Google
 
Web itpro-blogger.blogspot.com
水曜日, 2月 18, 2009

[XML or XSLT]属性値の出力

▼質問
livedoorの気象データ提供サービス「Weather Hacks」を試しているんだ。

下記のXMLファイルにあるtitle属性の値をXSLTを使って出力したいんだ。

http://weather.livedoor.com/forecast/rss/forecastmap.xml

どうしたらできるか教えてくれ!

▼回答
次のプログラムを参考にしてくれ!

・main.xml
<?xml version="1.0" encoding="Shift_JIS" ?>
<?xml-stylesheet type="text/xsl" href="main.xsl" ?>
<forecastmap_list>
<title>livedoor 天気情報(1次細分区定義表)</title>
<forecastmap href="http://weather.livedoor.com/forecast/rss/forecastmap.xml"/>
</forecastmap_list>





・main.xsl
<?xml version="1.0" encoding="Shift_JIS" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:param name="area_title" />
<xsl:template match="/">
<html>
<head>
<title><xsl:value-of select="forecastmap_list/title" /></title>
</head>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="forecastmap_list">
<xsl:apply-templates select="title" />
<table border="3">
<xsl:apply-templates select="forecastmap" />
</table>
</xsl:template>

<xsl:template match="title">
<h1><xsl:value-of select="." /></h1>
</xsl:template>
<xsl:template match="forecastmap">
<tr>
<th>地方名</th>
<th>都道府県名</th>
<th>観測地点名</th>
</tr>
<xsl:variable name="map" select="document(@href)" />
<xsl:for-each select="$map">
<xsl:apply-templates />
</xsl:for-each>
</xsl:template>

<xsl:template match="area">
<xsl:apply-templates>
<xsl:with-param name="area_title" select="@title" />
</xsl:apply-templates>
</xsl:template>

<xsl:template match="pref">
<xsl:param name="area_title" select="$area_title" />
<xsl:apply-templates>
<xsl:with-param name="area_title" select="$area_title" />
</xsl:apply-templates>
</xsl:template>

<xsl:template match="city">
<xsl:param name="area_title" select="$area_title" />
<tr>
<td><xsl:value-of select="$area_title" /></td>
<td><xsl:value-of select="parent::pref/@title" /></td>
<td>
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="@source" />
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:value-of select="@title" />
</xsl:element>
</td>
</tr>
</xsl:template>

</xsl:stylesheet>





■参考サイト
XSLT > 要素テキスト・属性値の出力 @みっちーわーるど
http://www1.mahoroba.ne.jp/~mitt/xml/xslt/step06.htm
[Think IT] 第2回:APIを使ったブログパーツを作ろう! (1/3)
http://thinkit.jp/article/850/1/
XSLTスタイルシート書き方講座 応用編(2):XMLデータの埋め込みと相互参照
http://www.atmarkit.co.jp/fxml/tanpatsu/10xslt/xslt06.html






Comments: コメントを投稿

<< Home

This page is powered by Blogger. Isn't yours?