我在需要针对 XSD 验证的 List 对象中有 XML。到目前为止,我只能验证 XML 文件。截至目前,我正在将我的列表写入一个临时文件并验证该临时文件。我真的很想消除对那个临时文件的需要。我的问题是 javax.xml.validation.Validator.validate 需要一个 Source,但我不知道如何将 List 放入 Source。
下面是我使用临时文件的工作源。
static String validate(List<String> xmlData, Schema schema) throws Exception {
File tmpFile = File.createTempFile("temp", ".xml"); // TODO: delete
StringBuilder exceptionList = new StringBuilder();
try {
Validator validator = schema.newValidator();
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler()
{
@Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
// TODO: remove this block
FileWriter fr = new FileWriter(tmpFile);
for (String str: xmlData) {
fr.write(str + System.lineSeparator());
}
fr.close();
//
validator.validate(new StreamSource(tmpFile)); // TODO: Here need xmlData instead
if (! exceptions.isEmpty() ) {
exceptions.forEach((temp) -> {
exceptionList.append(String.format("lineNumber: %s; columnNumber: %s; %s%s",
temp.getLineNumber(),temp.getColumnNumber(),temp.getMessage(),System.lineSeparator()));
});
}
return exceptionList.toString();
} catch (SAXException | IOException e) {
e.printStackTrace();
throw e;
} finally {
if (tmpFile.exists()) { tmpFile.delete(); } // TODO: delete
}
}
编辑:为了后代,这是新代码:
static String validate(String xmlData, Schema schema) throws Exception {
Reader sourceReader = null;
StringBuilder exceptionList = new StringBuilder();
try {
Validator validator = schema.newValidator();
final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
validator.setErrorHandler(new ErrorHandler()
{
@Override
public void warning(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException
{
exceptions.add(exception);
}
});
sourceReader = new StringReader(xmlData);
validator.validate(new StreamSource(sourceReader));
if (! exceptions.isEmpty() ) {
exceptions.forEach((temp) -> {
exceptionList.append(String.format("lineNumber: %s; columnNumber: %s; %s%s",
temp.getLineNumber(),temp.getColumnNumber(),temp.getMessage(),System.lineSeparator()));
});
}
return exceptionList.toString();
} catch (SAXException | IOException e) {
e.printStackTrace();
throw e;
} finally {
if (sourceReader != null) { sourceReader.close(); }
}
}