JAXB的Eclipse外掛程式(.xsd檔案到java類的映射)
一、JAXB的Eclipse外掛程式的:https://jaxb-workshop.dev.java.net/servlets/ProjectDocumentList?folderID=4962&expandFolder=4962&folderID=0
二、外掛程式的使用說明:https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
三、執行個體
1、databaseInfo.xsd檔案
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3school.com.cn" xmlns="http://www.w3school.com.cn"
elementFormDefault="qualified">
<xs:element name="database">
<xs:complexType>
<xs:sequence>
<xs:element name="info" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="ip" type="xs:string" />
<xs:element name="port" type="xs:string" />
<xs:element name="databaseName" type="xs:string" />
<xs:element name="userName" type="xs:string" />
<xs:element name="password" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
2、右鍵點擊“databaseInfo.xsd”檔案
3、下一步
4、下一步
5、“Finish”之後
6、重新整理項目
7、xmlOperation.java對XML的讀寫操作
package com.channelsoft.xml.operation;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.channelsoft.xml.Database;
import com.channelsoft.xml.ObjectFactory;
public class xmlOperation
{
/**
*從XML檔案讀
*/
public void readFromXML()
{
JAXBContext jc;
try
{
jc = JAXBContext.newInstance("com.channelsoft.xml");
Unmarshaller u = jc.createUnmarshaller();
Database info = (Database) u.unmarshal(new File("e:\\info.xml"));
for(int i=0;i<info.getInfo().size();i++)
{
System.out.println(info.getInfo().get(i).getIp());
System.out.println(info.getInfo().get(i).getPort());
System.out.println(info.getInfo().get(i).getDatabaseName());
System.out.println(info.getInfo().get(i).getUserName());
System.out.println(info.getInfo().get(i).getPassword());
}
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
/**
* 建立並寫入XML檔案
*/
public void saveToXML()
{
try
{
ObjectFactory of = new ObjectFactory();
Database database = of.createDatabase();
Database.Info info= of.createDatabaseInfo();
info.setIp("10.130.14.142");
info.setPort("1433");
info.setDatabaseName("hrinfo");
info.setUserName("sa");
info.setPassword("dibin");
Database.Info info1= of.createDatabaseInfo();
info1.setIp("10.130.14.49");
info1.setPort("1433");
info1.setDatabaseName("hrinfo");
info1.setUserName("sa11");
info1.setPassword("dibin11");
database.getInfo().add(info);
database.getInfo().add(info1);
JAXBContext jc = JAXBContext.newInstance("com.channelsoft.xml");
Marshaller ms = jc.createMarshaller();
ms.setProperty("jaxb.encoding", "GB2312");
ms.setProperty("jaxb.formatted.output", true);
ms.marshal(database, new File("e:\\info.xml"));
}
catch (Exception e)
{
}
}
public static void main(String[] args)
{
new xmlOperation().saveToXML();
new xmlOperation().readFromXML();
}
}
原始碼下載:http://download.csdn.net/detail/a9529lty/4028420