一.XMLBeans
基於XML開發的技術很多,常見的如Dom4j(JBoss用),Castor,Common-Degister(Struts用),XMLBeans.關於這些的比較網上很多.這里談談XMLBeans的用法.
XMLBeans的官方地址(http://xmlbeans.apache.org/).上面有它的詳細介紹和用法.
二 適用的場合
從使用的經驗來看,XMLBeans比較適合處理具有復雜Schema定義的xml,如SAML,Liberty等.而簡單的XML結構用Dom4j或者Castor XML Mapping 都很容易處理.
因此如果你要處理一個很復雜的Schema定義,選擇XMLbeans就比較好.
三. XMLBeans 的使用過程
1.要熟悉XML Schema. 這本書值得推薦: XML 模式權威教程 http://www.china-pub.com/computers/common/info.asp?id=8908)
2.從Schema 自動映射到 Java 對象.
這個步驟可以用XMLbeans的生成工具.
相關的Maven腳本如下:
<!--==================================================================-->
<!-- XMLBeans -->
<!--==================================================================-->
<goal description="xmlbeans generate " name="project:xmlbeans-gen" >
<echo>+---------------------------------------------------+</echo>
<echo>| XMLBeans genreating....... | </echo>
<echo>+---------------------------------------------------+</echo>
<taskdef name="xmlbean"
classname="org.apache.xmlbeans.impl.tool.XMLBean"
classpathref="maven.dependency.classpath"/>
<xmlbean srcgendir="${project.xmlbeans.srcgendir}"
classgendir="${project.xmlbeans.classgendir}"
destfile="${project.xmlbeans.destfile}" debug="true"
classpathref="maven.dependency.classpath" >
<fileset dir="${project.xmlbeans.schemas}" />
</xmlbean>
<!--
<path id="{maoxiang.xmlbeans.srcgendir" location="${maoxiang.xmlbeans.srcgendir}"/>
<maven:addPath id="maven.compile.src.set" refid="maoxiang.xmlbeans.srcgendir"/>
-->
</goal>
這個腳本調用XMLBeans的ant腳本(看xmlbeans文檔),生成了一個可以處理Schema的框架.
3. 使用XMLBeans 解析 xml
根據Schema的生成框架,就可以處理符合該Schema定義的XML實例了.這點和Eclipse下的EMF框架十分類似.
XMLBeans框架的兩個最重要的方法:
a) Factory 用來解析XML的,如 PortletAppType portletApp = PortletAppType.Factory.parse(file); 需要提醒的是,
one: parse 的參數雖然可以是各種類型,不過最好是 Stream型. 如果直接是File型,在web環境下,會報錯為 Content is not allowed in prolog.
two: 在Jboss下使用時,不需要使用jaxen這個包.
b) XmlText() 可以將對象的數據導出為xml格式,而且不一定是要根元素.
看看下面的代碼片斷:
從 portlet.xml中讀取啟動參數.
public static Properties getInitParamProps(PortletType portlet) {
Properties props = new Properties();
InitParamType[] inits = portlet.getInitParamArray();
for (int i = 0; i < inits.length; i++) {
props.setProperty(inits[i].getName().getStringValue(), inits[i]
.getValue().getStringValue());
}
return props;
}
4.總結
使用XMLBeans處理XML,簡單.高效(可以看看xmlbeans架構師的blog:http://davidbau.com/).比較難的在於如果要處理簡單的xml結構,你還得定義一個schema方便自動產生xmlbeans框架. 而Schema本身就是一種語言,建議采用 XML Spy(home edition 是免費的) 來編寫Schema.
下面這個Schema就是我的Portal Layout的Schema,用XMLBeans來處理的效果很好.