【发布时间】:2011-01-01 15:01:07
【问题描述】:
我有以下课程:
package com.somedir.someotherdir;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
public class SchemaValidator
{
private static Logger _logger = Logger.getLogger(SchemaValidator.class.getName());
/**
* @param file - the relative path to and the name of the XML file to be validated
* @return true if validation succeeded, false otherwise
*/
public final static boolean validateXML(String file)
{
try
{
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema();
Validator validator = schema.newValidator();
validator.validate(new StreamSource(file));
return true;
}
catch (Exception e)
{
_logger.log(Level.WARNING, "SchemaValidator: failed validating " + file + ". Reason: " + e.getMessage(), e);
return false;
}
}
}
我想知道我到底应该使用schema.newValidator("dir/to/schema.xsd") 还是当前版本可以?我读到有一些 DoS 漏洞,也许有人可以提供更多信息?另外,路径必须是绝对的还是相对的?
大多数要验证的 XML 都有自己的 XSD,所以我想阅读 XML 本身中提到的架构 (xs:noNamespaceSchemaLocation="schemaname.xsd")。
仅在启动或手动重新加载(服务器软件)期间进行验证。
【问题讨论】:
-
你们能不能停止重新格式化我的代码并给出一些答案??
-
“大多数要验证的 XML 都有自己的 XSD,所以我想阅读 XML 本身中提到的架构”也许这是相关的:stackoverflow.com/questions/2829105/…
-
可能相关,但不是我需要的。我只需要验证它,我在问这种方式是否好或是否需要任何修复。您的代码需要更多的类/方法,而这并不是我想要的。
-
@Alberto - “正确”是一个主观术语。我有我的代码风格,我不喜欢别人出于任何原因触碰它。此外,这在这个问题上并不重要。
标签: java xml xsd xsd-validation