How To Validate XML String against XSD Without Writing To A File

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources

This post shows how to validate XML string data against XSD files in Java. Most of the time, we work directly with XML files instead of string format. We point to an XML file and validate it against XSDs. However, we can validate XML content as a string against XSDs files without converting it to a file.

Validate XML Files Against XSDs

To make a point, consider the following codes. The codes refer to a file instead of a string, and the xmlFilePath variable points to a file.

Marshall to JAXB Object To String Or Craft An XML String

First, we need codes to convert a JAXB object to a String object. We can do this by marshaling an object to a StringWriter. Alternatively, we could craft XML data as a string. For this post, convert a JAXB object to a string object. Consider the following method.

From the StringWriter object, we can generate a String object.

Validate XML String

We can use the String object to compare against an XSD. Consider the following codes. Notice we use a string that represents an XML. See lines 10 – 13. However, the XSDs are still in a file.

Validate XML String Usage

Finally, we can put the methods together and test things out. Consider the following codes. Given a JAXB class, we can an object of that class. Then, we pass that object to the marshalObjectToString method. Next, we get a string, and we give it to the validate method where the validation takes place.

If the string has errors or does not conform to the XSDs, the codes return an Exception. Otherwise, the application runs past that call to the validate method.

And that’s how we can validate XML string instead of using XML files. Which technique to use then? It depends on your requirements. Generally, if the XML data is relatively small, we can use XML string instead. Otherwise, use XML files, especially for background processing.

You Might Also Like