简体   繁体   中英

Is there any best way to validate generated XML against XSD in Java

I'm generating the xml using Javax Marshaller. I'm looking for the way to validate the generated XML agaisnt XSD. I found gradle plugin to do this. But I couldnt use this plugin,because it is giving some error

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

My build.gradle file:

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

Are there any better ways to do this. I was going through this link What's the best way to validate an XML file against an XSD file? . Most of the answers are from 2008, I'm just curious whether any better ways available now to do this.

You are using JAXB, which is the "standard" way to work with XML in Java. This example code shows more than one package of generated (by xjc) Java classes and more than one XSD that you are validating against, as well as setting properties on the 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);

Note that the JAXBContext and Schema are thread safe and can be created once and reused forever by multiple threads, usually in a static initializer. A new marshaller should generally be created for each document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM