Подходящая XML-схема для Marshaller setSchema - PullRequest
2 голосов
/ 22 ноября 2010

Мне трудно найти правильную схему (для проверки структуры и типов данных) простых классов . Например, я мог получить ответ для Employee класса с schemagen (поставляется с JDK), но все равно не смог заставить его работать для 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 Ответ

2 голосов
/ 22 ноября 2010

Ниже приведен пример того, как создать схему XML с использованием JAXBContext:

Сначала вы должны создать класс, который расширяет 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-схемы.

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

Для получения дополнительной информации см .:

...