有没有最好的方法来验证Java中针对XSD生成的XML

时间:2016-10-17 19:16:49

标签: java xml gradle xsd xsd-validation

我正在使用Javax Marshaller生成xml。我正在寻找验证生成的XML agaisnt XSD的方法。我发现gradle插件可以做到这一点。但我不能使用这个插件,因为它给出了一些错误

Could not resolve gradle.plugin.com.github.ramonwirsch:fopRenderer:0.1.7

我的build.gradle文件:

buildscript {
  repositories {
      jcenter()  
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "gradle.plugin.com.github.ramonwirsch:fopRenderer:0.1.7"
  }
}

apply plugin: "com.github.ramonwirsch.FopRenderer"
apply plugin: 'java'
apply plugin: 'eclipse'

sourceCompatibility=1.8
targetCompatibility=1.8

project.ext {
    app_name='XSD-XML'
    build_date=new Date().format("yyyyMMddHHmm")
    release_number='R1.0'
    rc_build="${System.env.BUILD_NUMBER}"//look for BUILD_NUMBER in env (set by Jenkins)
    generatedSrcDir = file("$buildDir/generated-src")   
    jaxb_schema='src/main/resources/xsd'
    jaxbTargetDir = generatedSrcDir

}

repositories {  
// removed corporate repository details for security
jcenter()

}

configurations {
    jaxb    
}

dependencies {
    // Needed to generate JAX binding code
    jaxb 'com.sun.xml.bind:jaxb-xjc:2.2.4-1'

}

def generatedResources = 'src/main/generated'

task jaxb(){
    description 'Converts xsds to classes'
    def jaxbTargetDir = file( generatedResources )
    jaxbTargetDir.deleteDir()

    doLast {
        jaxbTargetDir.mkdirs()

        ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath)
        ant.jaxbTargetDir = jaxbTargetDir

        ant.xjc(destdir: '${jaxbTargetDir}', package: 'com.pavan.xml.java.binding') {
                schema(dir:'src/main/resources/xsd', includes: '*.xsd')
        }       
    }
}

task generateSources(dependsOn: jaxb) {
    description 'generates the resources defined by the external xsd\'s'
}

sourceSets {
    main {
        java {
            srcDirs = ['src/main/java', 'src/main/generated']
        }
    }
}

compileJava.dependsOn jaxb

有没有更好的方法来做到这一点。我正在浏览这个链接 What's the best way to validate an XML file against an XSD file?。大多数答案来自2008年,我只是好奇现在是否有更好的方法可以做到这一点。

1 个答案:

答案 0 :(得分:2)

您使用的是JAXB,这是"标准"在Java中使用XML的方法。此示例代码显示了多个生成的(通过xjc)Java类包和您要验证的多个XSD,以及在Marshaller上设置属性。

// This part can be in a static initializer, with `jaxbContext` and `schema` as static variables.
JAXBContext jaxbContext = JAXBContext.newInstance("package1:package2");
try (InputStream xsdStream1 = EraMarshallingService.class.getResourceAsStream("/a.xsd");
        InputStream xsdStream2 = EraMarshallingService.class.getResourceAsStream("/b.xsd");
        InputStream xsdStream3 = EraMarshallingService.class.getResourceAsStream("/c.xsd");) {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new Source[] { new StreamSource(xsdStream1), new StreamSource(xsdStream2),
                new StreamSource(xsdStream3));
}

// This part should be done for each document.
Marshaller marshaller = getJaxbContext().createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setSchema(schema);
marshaller.marshal(jaxbRootElement, whereTheOutputIsGoing);

请注意,JAXBContext和Schema是线程安全的,可以创建一次并由多个线程永久重用,通常在静态初始化程序中。通常应为每个文档创建一个新的编组程序。