以下是我們用來使用JAXB轉換爲/從XML轉換爲XML的類的副本,沒有使用XSD。 (我們也使用JAXB來生成我們的XSD)。
編輯:我只是重讀這個問題。如果您要問如何從該XML中生成Java源代碼,那麼您將不得不自己弄清楚,或者使用XSD並使用JAXB將其轉換爲類。如果您已經擁有該類,並且想要將XML轉換爲Java對象,那麼我的代碼將適用於您。
package com.mycompany.types;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlTransient;
/**
* Utility class to make it convenient to marshal and unmarshal the classes
* generated by JAXB.
*/
@XmlTransient
public final class Utility {
//
// Static initialization
//
static {
try {
JAXB_CONTEXT = JAXBContext.newInstance(TestClass.class);
// The following fails with a javax.xml.bind.JAXBException.
// class mycompany.types.TestClass nor any of its super class is known
// to this context.
// JAXB_CONTEXT =
// JAXBContext.newInstance("com.mycompany.types",
// Utility.class.getClassLoader());
}
catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
//
// Constructors
//
//
// Hidden constructor that prevents an object from being created.
//
private Utility() {
// Do nothing.
}
//
// Additional methods
//
/**
* Unmarshals an XML string to a TestClass object.
*
* @param xml the XML string to parse
* @return the resulting TestClass
* @throws JAXBException if there are XML errors
*/
public static TestClass parseTestClass(String xml) throws JAXBException {
Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
return (TestClass)unmarshaller.unmarshal(new StringReader(xml));
}
/**
* Marshals a TestClass object to an XML string.
*
* @param testClass
* @return the resulting XML string
* @throws JAXBException if there are XML errors
*/
public static String printTestClass(TestClass testClass) throws JAXBException {
Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(testClass, writer);
return writer.toString();
}
//
// Attributes
//
private static final JAXBContext JAXB_CONTEXT;
}
但是你可以生成像XML實例的XSD。 –
以下示例應該有所幫助:http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted –