0

我正在尝试使用以下代码块针对 XML 模式验证简单的 XML 文件。我遇到了一个例外

org.xml.sax.SAXParseException: cvc-elt.1: 
    Cannot find the declaration of element 'Applications'

并且想知道是否有人知道为什么会这样。(当我尝试查看模式加载后的内容时,我看到一堆语法对象或类似的东西,没有任何迹象表明模式已正确加载。是这样吗?如果我尝试加载一个不存在文件名的架构,它给了我一个找不到文件的异常......所以当给出正确的文件名时,我得到它正在寻找正确的架构)

public void getPriceSummaryInfo(){
        Document doc = null;
        try {
            File fXmlFile = new File("testXML.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(fXmlFile);
        } 
        catch (Exception e) {
            e.printStackTrace();
        }

        try {
        Schema schema = getSchema("testSchema.xsd");
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(doc));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Schema getSchema (String xsdPath) throws Exception {
        assert xsdPath != null : "XML schema path is null.";
        SchemaFactory fact = 
                SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Schema schema;
        try {
            schema = fact.newSchema(new StreamSource(new File(xsdPath)));
        }
        catch (SAXException e) {
            throw new Exception(
                    "Unable to find target schema to validate XML.", e);
        }
        return schema;
    } 

xml 和 xsd 文件是:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://www.randomthing.com"
            xmlns="http://www.randomthing.com"
            elementFormDefault="qualified">

    <xsd:element name="Applications">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="Application" minOccurs="0" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

    <xsd:element name="Application">
        <xsd:annotation>
            <xsd:documentation>
             blah
            </xsd:documentation>
        </xsd:annotation>
       <xsd:complexType>
            <xsd:attribute name="id" type="xsd:long" use="required"/>
            <xsd:attribute name="name" type="xsd:string" use="required"/>
            <xsd:attribute name="order" type="xsd:long" use="required"/>
        </xsd:complexType>    
    </xsd:element>
</xsd:schema>  



<?xml version="1.0" encoding="UTF-8"?>
<Applications xmlns ="http://www.randomthing.com"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.randomthing.com testSchema.xsd">

    <Application id="3" name="Blah" order="2">
    </Application>
</Applications>

将不胜感激任何指针!谢谢

4

1 回答 1

1

您应该使用名称空间解析文档,您在加载时会丢失它们。

dbFactory.setNamespaceAware(true);
于 2012-06-13T23:34:48.357 回答