Tag Archives: Validation

Validating XML node against a XSD schema

Sometimes you need to make sure a part of the xml document (more precisely a node and all node’s children)  are valid according to a given schema. So how this can be done, as XML validators tend to work on document basis (there seems to be something called XML fragments, but haven’t yet found a way to validate the nodes using xml fragments) ?

The workflow is simple:

  1. load the xsd file we want to validate against. For this I’ll use the handy class which searches the classpath for the given resource.
  2. transform the node into xml document.
  3. validate the document against the schema.
For transforming the xml node to document, first we’ll transform it into a string, with this handy method found here:
public static String xmlToString(Node node)
            Source source = new DOMSource(node);
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);
            return stringWriter.getBuffer().toString();
        catch (TransformerConfigurationException e)
        catch (TransformerException e)

        return null;

then we’ll use this string as a stream to create the document from and validate against the schema as bellow:

StringReader r = new StringReader(xmlToString(node));
validator.validate(new StreamSource(r));

The entire code is attached here (as example only, in production you’ll probably have to close the open input streams returned by the ClassPathSearcher class)