java - 在 java 中使用 XSD 进行 XML 验证

标签 java xml xsd xsd-validation

我有以下类(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/

相关文章:

java - 无法启动 WAR,嵌套异常是 java.lang.NoClassDefFoundError :

javascript - 使用 xml.setNamespace() 时不添加 namespace

java - 为什么在 Java 中无法对已删除类型进行拆箱?

python - 在Python中解析没有 'root'节点的XML文件

python - 使用 BeautifulSoup 循环列表并创建 XML 标签

xml - 处理 JAXB 枚举键名

Java 通过导入针对 xsd 验证 xml

xml - 在 xsd 中使用 ="optional"是多余的吗?

java - Xtext运行时编译

java - 为什么 Android Studio 自动导入内联类而不是在我的代码顶部?