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();
}
}