您可以通過自動化的JAXB這個過程中節省您的編碼時間:
創建使用以下鏈接爲您的XML提供一個XML模式,並將其保存爲輸出。XSD文件: http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx
運行批處理腳本文件(命名爲output.bat)使用JDK作爲唯一的JDK有xjc.exe工具(填寫下面從項目的根文件夾(。)必要的細節):
"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
然後,您可以在下面創建幾個有用的方法來操作對象:
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);
}
}
來源
2011-03-16 14:39:25
eee
希望你會在@Blaise :)我看看XmlPath,但無法找到如何查找給定ID的名稱。所以當解組第一個'Channel'時,XPath我想拿起名字是'ChannelName [id =「1」]/name',但是看不到如何插入'id'。我會有一個現在看看你的博客。 – andyb 2011-03-16 12:53:31
@andyb - 我們目前正在開發一個相關功能(請參閱https://bugs.eclipse.org/339596)。初始階段針對屬性上的條件(即ChannelName [@ id =「1」]/Name)。你需要組隊還是解組? – 2011-03-16 13:56:35
@Blaise - 我只需要解組,看起來謂詞特徵可能是解決方案,因爲我需要從文檔中其他位置的元素中獲取數據?另外,我看了你的(優秀)博客,幾乎有MOXy在春季工作。花了一段時間讓我瞭解了jaxb.properties和jaxb.index文件。我目前正在得到'class org.springframework.oxm.jaxb.Jaxb2Marshaller $ ByteArrayDataSource需要一個零參數構造函數例外。我正在使用Eclipse持久性服務2.3.0.v20110312-r9123 – andyb 2011-03-16 14:51:47