解決jdom輸出時產生無意義(空白)Namespace之問題

在新版的jdom(我用的時候是1.1)中,使用XMLOutputter來輸出整個XML Document時,在Element上會產生空白內容的Namespace,像是這樣:

<bean xmlns=""></bean>
不管是呼叫Element的removeNamespaceDeclaration()或是設定NO_NAMESPACE都沒有用,甚至在create element之後呼叫remove attribute()去remove xmlns屬性也不行,這案情不單純阿...。

後來Google到一篇,裡面說到jdom新版有bug,要去source code裡面解決,不過也沒說是什麼問題,只好自己來啦!好險並不是很困難,原因在於XMLOutputter這支code裡面出了問題,在XMLOutputter中,有一個方法叫printNamespace,裡面原本的code有一段是長這樣:

out.write(" xmlns");
if (!prefix.equals("")) {
out.write(":");
out.write(prefix);
}
out.write("=\"");
out.write(escapeAttributeEntities(uri));
out.write("\"");
namespaces.push(ns);


很明顯有了錯,改成下面這樣就可以了:
if (!prefix.equals("")) {
out.write(" xmlns");
out.write(":");
out.write(prefix);
out.write("=\"");
out.write(escapeAttributeEntities(uri));
out.write("\"");
}
namespaces.push(ns);

Share this post!

Bookmark and Share

0 意見: