XMLライブラリの紹介 (2)
前のエントリからかなり間が空いてしまいましたが、XML ライブラリの紹介の続きです。
読み込んだXML文書のツリー構造をたどって各要素に対する処理を行うのは、手間がかかります。
今回は、フレームワークを利用して XML 文書を解釈 (interpret) する方法について説明します。
1. xml::Interpreter の継承
まず、xml::Interpreter を継承して、独自のインタプリタクラスを定義します。
ユーザは、xml::Interpreter の仮想関数 Proc をオーバーライドすることで、その動作を定義することができます。
例として、XHTMLファイルを読み込み、以下の属性値を抜き出して表示するインタプリタを作成してみましょう。
- a 要素の href 属性
- img 要素の src 属性
この場合は、要素に対する動作だけを記述すればよいので、オーバライドするのは Proc の書式 4. のみとなります。
| MyInterpreter.h |
#include "xml/xmlInterpreter.h"
//ユーザ定義XMLインタプリタ
class MyInterpreter : public xml::Interpreter {
protected:
//virtual: Interpreter
virtual void Proc(const xml::Elem*);
}; |
| MyInterpreter.cpp |
#include "MyInterpreter.h"
#include "narita/String.h"
#include "xml/xmlElem.h"
//要素の処理
void MyInterpreter::Proc(const xml::Elem* lpElem){
const String& name =lpElem->Name();
if (name == "a"){
String href =lpElem->Attribute("href");
if (href) puts(href);
}
else if (name == "img"){
String src =lpElem->Attribute("src");
if (src) puts(src);
}
xml::Interpreter::Proc(lpElem);
return;
} |
2. 処理の実行
それでは実際に、作成したインタプリタを使用してこのページのXHTMLデータ を解釈してみましょう。
上記リンクを右クリックして「対象をファイルに保存(A)...」を選び、"sample.xml" という名前で保存してください。
#include "xml/xmlDocument.h"
#include "xml/xmlParseException.h"
#include "MyInterpreter.h"
int main(){
//XMLデータの読み込み ------------------------------
xml::Document* lpDoc;
try {
lpDoc =xml::Document::load("sample.xml");
}
catch (xml::ParseException& e){
e.Print(stderr);
exit(EXIT_FAILURE);
}
//インタプリタ処理 ----------------------------------
MyInterpreter i;
try {
i.Init(lpDoc);
i.Run();
}
catch (xml::InterpretException& e){
e.Print(stderr);
exit(EXIT_FAILURE);
}
//データの解放
xml::Document::release(lpDoc);
return 0;
} |
http://www.codelogy.org//img/codelogy.png http://www.codelogy.org/ http://www.codelogy.org/archives/2007/05/codelogy.html http://www.nowhere.co.jp/~narita/library/xml/doc/Interpreter/index.html http://www.nowhere.co.jp/~narita/library/xml/doc/Interpreter/reference/index.html#PROC http://www.nowhere.co.jp/~narita/library/xml/doc/Elem/reference/index.html#NAME./xml.html http://www.nowhere.co.jp/~narita/library/xml/doc/Document/reference/index.html#LOAD http://www.nowhere.co.jp/~narita/library/xml/doc/Interpreter/reference/index.html#INIT http://www.nowhere.co.jp/~narita/library/xml/doc/Interpreter/reference/index.html#RUN http://www.nowhere.co.jp/~narita/library/xml/doc/Document/reference/index.html#RELEASE http://www.codelogy.org/archives/2006/01/xml.html http://www.codelogy.org/archives/2007/05/codelogy.html http://www.codelogy.org/ http://www.codelogy.org/archives.html http://www.codelogy.org/atom.xml http://www.sixapart.jp/movabletype/ http://validator.w3.org/check?uri=referer http://www.w3.org/Icons/valid-xhtml10 |
このように、できるだけ少ない手間でXMLデータの処理を記述できるようフレームワークを設計してみました。
「ここをこうした方が良い」などの意見があれば、ぜひお寄せください。
担当: 成田

コメントを投稿