适用于Marshaller setSchema的XML模式

时间:2010-11-22 01:24:25

标签: java xml xsd jaxb

我很难弄清楚简单classes的正确架构(验证结构和数据类型)。例如,我可以使用Employee(随JDK提供)获得schemagen类的答案,但仍无法使其适用于HumanResources

我正在尝试将Employee类实例的集合序列化为XML。为此,我创建了类HumanResources,其中包含Employee类元素的列表。例如:

    ArrayList<Employee> ems = getTestData();
    HumanResources hm = new HumanResources(ems);
    SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    JAXBContext jaxbContext = JAXBContext.newInstance(HumanResources.class);

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setSchema(sf.newSchema(new File("src\\server\\HumanResources.xsd")));
    marshaller.marshal( new JAXBElement<HumanResources>(
            new QName(null, "HumanResources"), HumanResources.class, hm), os);

1 个答案:

答案 0 :(得分:2)

下面是如何使用JAXBContext创建XML模式的示例:

首先,您必须创建一个扩展javax.xml.bind.SchemaOutputResolver的类。

public class MySchemaOutputResolver extends SchemaOutputResolver {

    public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
        File file = new File(suggestedFileName);
        StreamResult result = new StreamResult(file);
        result.setSystemId(file.toURI().toURL().toString());
        return result;
    }

}

然后使用此类的实例与JAXBContext来捕获生成的XML Schema。

Class[] classes = new Class[4]; 
classes[0] = org.example.customer_example.AddressType.class; 
classes[1] = org.example.customer_example.ContactInfo.class; 
classes[2] = org.example.customer_example.CustomerType.class; 
classes[3] = org.example.customer_example.PhoneNumber.class; 
JAXBContext jaxbContext = JAXBContext.newInstance(classes);

SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);

有关详细信息,请参阅: