直接觀看文章

JDOM XPath 的 Namespace 處理

三月 4, 2010

JDOM 的 XPath 並沒有辦法處理含有 Namespace 的 XML Document 物件,這使得在處理 XML 資料時往往沒辦法用 XPath 來快速抓取節點,因為 selectSingleNode()/selectNodes() 取回來的物件或集合都為空,昨天發狠決定要找出解決的方式,總算這問題有解了。

Jaxen 的 JDOMXPath 類別是 XPath 介面的實作,專門給 JDOM 的 XML Document 來進行 XPath 運算,這個介面有提供一個 method 叫 setNamespaceContext() 可以來傳入自訂的 Namespace 資訊,將 Namespace 的 prefix 與 URI 組成一 Map 後建立 SimpleNamespaceContext 類別並傳入即可︰


map = new HashMap();
map.put("hpMain", "http://www.daisy.org/z3986/2005/ncx/");
XPath itemXPath = new JDOMXPath("//hpMain:content");
itemXPath.setNamespaceContext(new SimpleNamespaceContext(map));

於是再利用這個 XPath 物件取 selectSingleNode() 或 selectNodes() 便可以順利傳回節點集合。請參考 XPath and Default Namespace handling 這篇文章,有介紹各類實作 XPath 的套件要怎麼解決 Namespace 的問題。

尚無迴響

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s

Follow

Get every new post delivered to your Inbox.