2012-12-14 30 views
9

我已按照this tutorial驗證XML文件。但是在驗證XML文件時我收到異常。我做錯了什麼?我的代碼:
XML模式:Java XML架構驗證:前綴未綁定

<?xml version="1.0" encoding="utf-8" ?> 

<!-- definition of simple elements --> 
<xs:element name="first_name" type="xs:string" /> 
<xs:element name="last_name" type="xs:string" /> 
<xs:element name="phone" type="xs:string" /> 

<!-- definition of attributes --> 
<xs:attribute name="type" type="xs:string" use="required"/> 
<xs:attribute name="date" type="xs:date" use="required"/> 

<!-- definition of complex elements --> 

<xs:element name="reporter"> 
    <xs:complexType> 
     <xs:sequence> 
      <xs:element ref="first_name" /> 
      <xs:element ref="last_name" /> 
      <xs:element ref="phone" /> 
     </xs:sequence> 
    </xs:complexType> 
</xs:element> 

<xs:element name="report"> 
    <xs:complexType> 
     <xs:attribute ref="type"/> 
     <xs:attribute ref="date" /> 
     <xs:sequence> 
      <xs:element ref="reporter" /> 
     </xs:sequence> 
    </xs:complexType> 
</xs:element> 

XML文件來驗證:

<?xml version="1.0" encoding="utf-8" ?> 
<report type="5" date="2012-12-14"> 
    <reporter> 
     <first_name>FirstName</firstname> 
     <last_name>Lastname</lastname> 
     <phone>+xxxxxxxxxxxx</phone> 
    </reporter> 
</report> 

Java源代碼來驗證:

import javax.xml.XMLConstants; 
import javax.xml.transform.Source; 
import javax.xml.transform.stream.StreamSource; 
import javax.xml.validation.*; 
import org.xml.sax.SAXException; 
import java.io.*; 

public class ProtocolValidator 
{ 
    public static void main(String [] args) throws Exception 
    { 
     Source schemaFile = new StreamSource(new File("schema.xsd")); 
     Source xmlFile = new StreamSource(new File("test_xml.xml")); 

     SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
     Schema schema = schemaFactory.newSchema(schemaFile); 
     Validator validator = schema.newValidator(); 

     try{ 
      validator.validate(xmlFile); 
      System.out.println(xmlFile.getSystemId() + " is valid"); 
     } 
     catch (SAXException e) 
     { 
      System.out.println(xmlFile.getSystemId() + " is NOT valid"); 
      System.out.println("Reason: " + e.getLocalizedMessage()); 
     } 
    } 
} 

例外,我接受:

Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/root/test/schema.xsd; lineNumber: 4; columnNumber: 50; The prefix "xs" for element "xs:element" is not bound. 
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)... 

回答

11

XML模式文件本身需要是有效的XML文檔。缺少外部模式元素和xs前綴的名稱空間聲明。

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <!-- schema elements here --> 
</xs:schema> 
2

此行添加到您的模式,只是下面的第一行:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 

...和結束標記,如架構中的最後一行:

</xs:schema>