简体   繁体   中英

How to input a variable with XML to validate against XSD

I have this code to make a validation of a XML file with a XSD. And this code works!

var schemaFile = new Packages.java.io.File("C:\\schema.xsd");
var url = new Packages.java.net.URL("file:C:\\input.xml");
var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(url);
var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
var schema = schemaFactory.newSchema(schemaFile);

var validator = schema.newValidator();

try {
    validator.validate(xmlFile);
    logger.info('valid');
} catch (err) {
    logger.error(err.toString());
}

But now, instead of using a XML file as input in here

var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(url);

I want to use a variable, passed before, that has a XML in it. If I write the variable there

var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(msg);

I get an error protocol

JavaException: java.net.MalformedURLException: no protocol:

This is because StreamSource needs a specified protocol, for a File it was easy (file:path). How can I put there a variable instead of a file?

The javax.xml.transform.stream.StreamSource can be constructed from a URL or a InputStream or a Reader. If the msg is your xml. Create a StringReader using that string and instantiate the StreamSource with it.

You can use the SAXSource class , which has a constructor that takes an InputSource argument.

There's an InputSource constructor that takes a Reader argument, so you can use that constructor and use the StringReader implementation.

In code:

var reader = new Packages.java.io.StringReader(msg);
var source = new Packages.org.xml.sax.InputSource(reader);
var xmlFile = new Packages.javax.xml.transform.sax.SAXSource(source);

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