XPathとは、XML中の要素を特定する方法を定めた規格です。XPathとは - IT用語辞典 e-Words
| 関数 | 機能 |
|---|---|
| contains(haystack, needle) | haystackにneedleが含まれていればtrueを返す |
| starts-with(haystack, needle) | haystackがneedleで始まればtrueを返す |
| ノード | 説明 | 式 |
|---|---|---|
| ルートノード root node |
最上位ノード | / |
| 要素ノード element node |
XMLの要素を表すノード | |
| 属性ノード attribute node |
要素内で指定された属性を表すノード | @ |
| テキストノード text node |
開始タグと終了タグで挟まれた文字列データ | text() |
| 処理命令ノード processing instruction node |
処理命令を表すノード | |
| コメントノード comment node |
コメントを表すノード | |
| 名前空間ノード namespace node |
名前空間を表すノード |
| 式 | 説明 |
|---|---|
| ノード名 | "ノード名"であるすべてのノードを選択 |
| / | ルートノードから選択 |
| // | 現在のノードから、階層と無関係に選択 |
| . | 現在のノードから選択 |
| .. | 芸材の親ノードから選択 |
| @ | 属性を選択 |
特定のclass属性を持つ要素にマッチさせるには、次のような方法があります。
//*[@class="foo"]//*[contains(@class,"foo")]//*[contains(concat(" ",@class," "), " foo ")]//*[contains(concat(" ",normalize-space(@class)," "), " foo ")]それぞれマッチする正確性が異なり、後の方がより正確になります。
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<a id="test">
<b>ABC</b>
<c>10</c>
<c>20</c>
</a>
XML文書
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" encoding="utf-8" />
<xsl:template match="/">
<xsl:value-of select="/a/b" /> <!-- XPath -->
</xsl:template>
</xsl:stylesheet>
XSLTスタイルシート。ファイル名は"style.xsl"
「ABC」と出力されます。
<xsl:value-of select="..."/>のselect属性の値を書き換えると、下表のように出力が変化します。
| XPath | 出力 |
|---|---|
/a/b |
ABC |
/a/b/text() |
ABC |
//a |
ABC 10 20 |
//b |
ABC |
/a/@id |
test |
/a/c |
10 |
/a/c[1] |
10 |
/a/c[2] |
20 |