我有以下类(class):
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 DTD DOS 攻击吗?如果是这样,网上有一些不错的文章:
XML 拒绝服务攻击和防御 http://msdn.microsoft.com/en-us/magazine/ee335713.aspx
来自IBM developerWorks. "Tip: Configure SAX parsers for secure processing" :
Entity resolution opens a number of potential security holes in XML.[...]
- The site where the external DTD is hosted can log the communication. [...]
- The site that hosts the DTD can slow the parsing [...] It can also stop the parse completely by serving a malformed DTD.
- If the remote site changes the DTD, it can use dafault attribute values to inject new content into the document[...] It can change the content of the document by redefining entity references.
我不确定它是否可以直接应用于你的程序,它可以为进一步调查提供一些线索
关于java - 在 java 中使用 XSD 进行 XML 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4574430/