要素オブジェクトの取得[XML DOM関数]

メモ:  Category:vb

ここでは、XMLから要素オブジェクトを取得する方法を見てみます。

サンプルとしてlivedoorのお天気情報サービス(Livedoor Weather Web Service / LWWS)を使用しています。

http://weather.livedoor.com/forecast/webservice/rest/v1?city=84&day=today

タグ名から要素オブジェクトを取得

特定のタグ名から要素オブジェクトを取得するには**GetElementsByTagName()**メソッドを使用します。

livedoorのお天気情報サービス(Livedoor Weather Web Service / LWWS)を例に取得して見ます。**GetElementsByTagName()**関数に’image’というタグ名を指定することで要素を取得します。

Dim weatherxml As New XmlDocument
weatherxml.Load("d:\v1.xml")

Dim nodeList As XmlNodeList = weatherxml.GetElementsByTagName("image")
For i As Integer = 0 To nodeList.Count - 1
    Trace.WriteLine(nodeList(i).InnerXml)
Next i

上記例では、imageタグの子要素が次のように出力されます。(出力結果が長いため折り返してあります。)

<title>曇時々晴</title>
<link>http://weather.livedoor.com/area/29/84.html?v=1</link>
<url>http://image.weather.livedoor.com/img/icon/9.gif</url>
<width>50</width>
<height>31</height>

<title>livedoor 天気情報</title>
<link>http://weather.livedoor.com</link>
<url>http://image.weather.livedoor.com/img/cmn/livedoor.gif</url>
<width>118</width>
<height>26</height>

ここで得られた結果は、ノードは要素(Element)でxml文書中に2箇所タグが出現します。取得できた要素がElementであるかどうかは、GetTypeメソッドでわかります。Elementの場合、System.Xml.XmlElementが返されます。

子要素の取得(ChildNodes)

要素オブジェクトを取得するもうひとつの方法は、**ChildNodes()**を使用することです。先ほどのimage要素から子要素を取得します。

Dim weatherxml As New XmlDocument
weatherxml.Load("d:\v1.xml")

Dim nodeList As XmlNodeList = weatherxml.GetElementsByTagName("image")
For i As Integer = 0 To nodeList.Count - 1
    Trace.WriteLine(nodeList(i).ChildNodes.Item(0).InnerText)
Next i

上記例では、imageタグの子要素から最初(インデックス 0)のタグを対象としています。

曇時々晴

livedoor 天気情報

bluenote by BBB