2008-12-31

XPath覚え書き

以下の内容くらいで以外に事足ります。

シンタックス 意味
// 先祖と子孫エレメントの連結
/ 親子を連結
* 全要素
tag[@xxx] tagの属性xxx
tag[n] n個目のtag(要素)
text() テキストの内容
.. 1階層上の要素

式の確認には、CPANモジュールのXML::XPathに付属のxpathを使います。xpathはコマンドとして使えるPerlスクリプトで、

xpath 入力ファイル xpath式
の形式で使用します。以下のHTMLで試してみます。

<body>
  <div class="hoge">
    abababa.
  </div>
  <div class="hoge">
    <p>
      <strong>
        <a href="http://www.google.com/">
          google
        </a>
      </strong>
    </p>
  </div>
</body>

入力: xpath foo.html '//a' 意味: リンクタグを選択
選択結果

<a href="http://www.google.com/">
            google

          </a>

入力: xpath foo.html '//div//strong'
意味: divの子孫のstrongを選択
選択結果

<strong>
          <a href="http://www.google.com/">
            google
          </a>

        </strong>

入力: xpath foo.html '//a/@href'
意味: aタグのhref属性を選択
選択結果

href="http://www.google.com/"

入力: xpath foo.html '//div[2]'
意味: 2つ目のdivを選択
選択結果

<div class="hoge">
      <p>
        <strong>
          <a href="http://www.google.com/">
            google
          </a>
        </strong>
      </p>
    </div>

入力: xpath foo.html '//div[@class="hoge"][2]/p/strong'
意味: classがhogeの2番目のdivを選択し、さらにその子要素のpの子要素のstrongを選択
選択結果

<strong>
          <a href="http://www.google.com/">
            google
          </a>
        </strong>

入力: xpath foo.html '//div//a/text()'
意味: divの子孫aのテキストを選択 選択結果

google

入力: xpath foo.html '//div//a/..'
意味: divの子孫aの1階層上の要素を選択 選択結果

<strong>
          <a href="http://www.google.com/">
            google
          </a>
        </strong>

さらに色んな選択方法とかは ここを参照してください。また、XPathの考え方はこちらが参考になりました。

Posted at 23:52 in | WriteBacks (4) | Edit