在開發過程中經常需要把一些配置文件進行合并。一般情況下這些配置文件都是使用xml格式進行存儲的。對配置文件進行合并,說到底就變成了對xml的合并。
有了這樣的需求就的好好想想有那些方案了。稍微的想了想(肯定不完整了)合并xml可行方案:
1、使用dom4j、sax等xml解析工具對需要合并的xml代碼進行分析、比較并合并。
<<Java中合并XML文檔的設計與實現>>(http://fanqiang.chinaunix.net/program/html/2005-06-16/3313.shtml)一文就是采用的這種方式實現了。
2、采用xslt對xml進行合并。
在這兩個技術中,我是重點的看了一下第二種。原因是以前對xslt有一點了解,而且不用我自己去控制遞規循環這樣比較容易出錯的環節。
還有就是使用 xslt 有很多很不錯的調試環境可以使用如 xmlspy,stylus studio 等。可以直接看到調試過程。最后有幸在網上看到了一個老外寫的一個用于合并 xml 的 xslt ( http://www2.informatik.hu-berlin.de/~obecker/XSLT/#merge )。用 xmlspy 跑了一下,當時感覺就是一個“爽”了得。狂喜過后,就開始思考想想如何用 java 實現這個 xslt 的轉換過程了。其實這也是一個很簡單的過程。使用 dom4j 用下面的代碼就可以實現:
Document?document,
String?stylesheet
)?
throws
?Exception?{
//
?load?the?transformer?using?JAXP
TransformerFactory?factory?
=
?TransformerFactory.newInstance();
Transformer?transformer?
=
?factory.newTransformer(
new
?StreamSource(?stylesheet?)
);
//
?now?lets?style?the?given?document
DocumentSource?source?
=
?
new
?DocumentSource(?document?);
DocumentResult?result?
=
?
new
?DocumentResult();
transformer.transform(?source,?result?);
//
?return?the?transformed?document
Document?transformedDoc?
=
?result.getDocument();
return
?transformedDoc;
}
就用這樣的代碼一跑,他居然,居然沒有得到我想要的結果。郁悶啊!直接想去找塊豆腐,一頭撞死算了。但是在死前還是要把這個問題解決掉。要不死也不甘心。簡單的分析一下,在xmlspy中可以使用,說明xslt肯定沒有問題。那有問題的肯定是xslt 處理器有問題。你有問題我換不就的了嗎。最后我換成了如下的情況:
?????? < groupId > dom4j </ groupId >
?????? < artifactId > dom4j </ artifactId >
?????? < version > 1.6.1 </ version >
???? </ dependency >
???? < dependency >
?????? < groupId > net.sf.saxon </ groupId >
?????? < artifactId > saxon </ artifactId >
?????? < version > 8.5.1 </ version >
???? </ dependency >
?? </ dependencies >
重新跑了一下,ok了。沒有問題了。
下面的任務就是對這個功能進行簡單的封裝一下。然需要xml合并的地方能夠很容易的調用他。