Xml Java DOM解析器验证不起作用

时间:2015-06-22 14:34:01

标签: java xml

我正在尝试使用DOM解析器验证xml。由于某种原因,解析器无法识别指定的命名空间。可能是什么问题?

它抛出错误:

Error: URI=null Line=5: cvc-elt.1: Cannot find the declaration of element 'ioc'.

代码:

String outputString = "<?xml version=\"1.0\" encoding=\"us-ascii\"?>\n" +
    "<ioc\n" +
    "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" +
    "xmlns:xsd='http://www.w3.org/2001/XMLSchema'\n" +
    "xmlns=\"http://schemas.mandiant.com/2010/ioc\" >\n" +
    "</ioc>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
    "http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.parse(new ByteArrayInputStream(outputString.getBytes("UTF-8")));

2 个答案:

答案 0 :(得分:1)

我不能说你提供的实现有什么问题,但这是我用来根据模式验证XML文档的方法(仅使用标准库)

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;


    /**
     * 
     * Purpose: validate an XML document against a schema
     * @param dom The org.w3c.dom.Document object representing the XML document
     * @param xsdPath The path to the XML schema file
     * @return True if the XML instance validates against the schema.
     */
    private static boolean validateXML(Document dom, String xsdPath){
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source schemaFile = new StreamSource(new File(xsdPath));
        try {
            Schema schema = factory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            // validate the DOM tree
            validator.validate(new DOMSource(dom));
        } catch (SAXException se) {
            se.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }

答案 1 :(得分:0)

解决方案是添加schemaLocation属性以及所有必需的依赖项。

xsi:schemaLocation="http://schemas.mandiant.com/2010/ioc 
http://schemas.mandiant.com/2010/ioc/ioc.xsd 
http://schemas.mandiant.com/2010/ioc/TR/ 
http://schemas.mandiant.com/2010/ioc/TR/ioc-TR.xsd"