这是一个类的副本,我们使用 JAXB 使用类而不是 XSD 与 XML 进行转换。(我们还使用 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;
}