1. 根据xsd生成java类
xsd文件
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
jxb:version="2.0">
<xsd:element name="Greetings" type="GreetingListType"/>
<xsd:complexType name="GreetingListType">
<xsd:sequence>
<xsd:element name="Greeting" type="GreetingType"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="GreetingType">
<xsd:sequence>
<xsd:element name="Text" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="language" type="xsd:language"/>
</xsd:complexType>
</xsd:schema>
pom文件
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/resources</schemaDirectory>
<schemaFiles>test.xsd</schemaFiles>
<outputDirectory>src/main/jaxb</outputDirectory>
<packageName>abadboy.com.jaxb</packageName>
<clearOutputDir>true</clearOutputDir>
</configuration>
</plugin>
</plugins>
</build>
2. marshal
private static void marshal() throws IOException {
ObjectFactory factory = new ObjectFactory();
GreetingListType greetingListType = factory.createGreetingListType();
GreetingType greetingType = factory.createGreetingType();
greetingType.setLanguage("English");
greetingType.setText("Hello");
GreetingType greetingType1 = factory.createGreetingType();
greetingType1.setLanguage("Chinese");
greetingType1.setText("World");
greetingListType.getGreeting().add(greetingType);
greetingListType.getGreeting().add(greetingType1);
File file = new File("file.xml");
OutputStream fileOutputStream = new FileOutputStream(file);
JAXB.marshal(greetingListType, System.out);
JAXB.marshal(greetingListType,fileOutputStream);
fileOutputStream.close();
}
3. unMarshal
private static void unMarshal() {
InputStream in = JaxbTest.class.getClassLoader().getResourceAsStream("file.xml");
GreetingListType greetingListType = JAXB.unmarshal(in, GreetingListType.class);
for (GreetingType greetingType : greetingListType.getGreeting()) {
System.out.println(greetingType.getLanguage()+" "+greetingType.getText() );
}
}
StringWriter sw = new StringWriter();
JAXB.marshal(xxxxxx, sw);
result = session.createTextMessage(sw.toString());