java - 适用于 Marshaller setSchema 的 XML 模式

标签 java xml xsd jaxb

我很难找出简单 classes 的正确模式(以验证结构和数据类型) .例如,我可以使用 schemagen(随 JDK 提供)为 Employee 类获得答案,但仍然无法让它为 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);

最佳答案

下面是如何使用 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 模式。

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

有关详细信息,请参阅:

关于java - 适用于 Marshaller setSchema 的 XML 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241504/

相关文章:

java - 如何解析 cvc-pattern-valid : Value '' is not facet-valid with respect to pattern problem

c# - 序列复杂类型中缺少必需元素时的 XSD 验证错误

java - 规则引擎根据多个条件过滤多个输入对象

java - 我如何检查哪些所有用户都登录到我的应用程序

xml - 我们可以将 XML 文件导入另一个 XML 文件吗?

python - 使用lxml库解析dtd文件(python)

c# - 如何在 C# 中动态创建 XML 架构?

java - 为什么它会得到这样的一点呢?

java - POI Java Excel解决方案——缩进值

xml - ScrollView 包装的 Nativescript GridLayout