JAXB でこのプロセスを自動化することにより、コーディング時間を節約できます。
以下のリンクを使用して XML の XML スキーマを作成し、 output.xsdファイル
として保存します: http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx
JDK のみがxjc.exeツールを備えているため (必要な詳細を入力します)、JDK を使用して、プロジェクトのルート フォルダー (.) から以下のバッチ スクリプト ファイル ( output.batという名前) を実行します。
"C:\Program Files\Java\jdk1.6.0_24\bin\xjc.exe" -p %1 %2 -d %3
どこ...
syntax: output.bat %1 %2 %3
%1 = target package name
%2 = full file path name of the generated XML schema .xsd
%3 = root source folder to store generated JAXB java files
例:
プロジェクトフォルダーが次のように編成されているとしましょう:
.
\_src
(.) からコマンド プロンプトで次のコマンドを実行します。
output.bat com.project.xml .\output.xsd .\src
いくつかのファイルが作成されます。
.
\_src
\_com
\_project
\_xml
|_ObjectFactory.java
|_Output.java
次に、以下のいくつかの便利なメソッドを作成して、Output
オブジェクトを操作できます。
private JAXBContext jaxbContext = null;
private Unmarshaller unmarshaller = null;
private Marshaller marshaller = null;
public OutputManager(String packageName) {
try {
jaxbContext = JAXBContext.newInstance(packageName);
unmarshaller = jaxbContext.createUnmarshaller();
marshaller = jaxbContext.createMarshaller();
} catch (JAXBException e) {
}
}
public Output loadXML(InputStream istrm) {
Output load = null;
try {
Object o = unmarshaller.unmarshal(istrm);
if (o != null) {
load = (Output) o;
}
} catch (JAXBException e) {
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
return load;
}
public void saveXML(Object o, java.io.File file) {
Output save = null;
try {
save = (Output) o;
if (save != null) {
marshaller.marshal(save, file);
}
} catch (JAXBException e) {
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
}
public void saveXML(Object o, FileOutputStream ostrm) {
Output save = null;
try {
save = (Output) o;
if (save != null) {
marshaller.marshal(save, ostrm);
}
} catch (JAXBException e) {
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
}
}