2009-08-28 72 views
1

我有一個Java xml驗證的問題。java xml驗證JDK 1.5 JDK 1.6的差異

我有以下的xsd:

<?xml version="1.0" encoding="utf-8"?> 
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="TEST"> 
    <xsd:complexType> 
     <xsd:sequence> 
     <xsd:element name="LAST_NAME"> 
      <xsd:simpleType> 
      <xsd:restriction base="xsd:string"> 
       <xsd:minLength value="1" /> 
       <xsd:maxLength value="30" /> 
      </xsd:restriction> 
      </xsd:simpleType> 
     </xsd:element> 
     <xsd:element name="FIRST_NAME"> 
      <xsd:simpleType> 
      <xsd:restriction base="xsd:string"> 
       <xsd:minLength value="1" /> 
       <xsd:maxLength value="20" /> 
      </xsd:restriction> 
      </xsd:simpleType> 
     </xsd:element> 
     <xsd:element name="DOB" nillable="true" type="xsd:date" /> 
     </xsd:sequence> 
    </xsd:complexType> 
    </xsd:element> 
</xsd:schema> 

和xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<TEST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <LAST_NAME>Lastname</LAST_NAME> 
    <FIRST_NAME>Firstname</FIRST_NAME> 
    <DOB xsi:nil="true"/> 
</TEST> 

我的驗證的(簡化)代碼:

boolean valid=true; 
try { 
    Source schemaSource = new StreamSource(xsdInputStream); 
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    Document document = parser.parse(xmlInputStream); 
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

    Schema schema = factory.newSchema(schemaSource); 

    Validator validator = schema.newValidator(); 
    try { 
     validator.validate(new DOMSource(document)); 
    } catch (SAXException e) { 
     logger.log(Level.INFO, e.getMessage(), e); 
     valid = false; 
    } 

} catch(Exception ex) { 
    logger.log(Level.SEVERE, ex.getMessage(), ex); 
    valid=false; 
} 

的testprogram有不同的行爲JDK 1.5和JDK 1.6。 xml在JDK 1.5中有效,但在JDK 1.6中無效。錯誤消息如下:

Element 'DOB' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xsi:nil' was found. 

哪個JDK是正確的?如何更改xml/xsd在兩者中都有效?

回答

1

嘗試在您的XSD中放置attributeFormDefault =「qualified」。這不應該有所作爲,但這是一個快速測試。

另外:您不要將DocumentBuilder設置爲名稱空間感知。這肯定會打破驗證,但它會打破1.5和1.6。

作爲一般性評論,解析時的驗證更有用,因爲您可以看到未通過驗證的內容的行號。下面的代碼做(schema是先前創建的):

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
dbf.setNamespaceAware(true); 
dbf.setValidating(false); 
dbf.setSchema(schema); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
+0

thx。 setNamespaceAware(true)解決了我的問題。 – asalamon74 2009-08-28 19:08:50

0

我會說這是Java 6中的錯誤,您可以始終把任何元素XSI屬性。

這是非常相似的這個bug,

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6790700

嘗試修復6u14。它很可能會解決你的問題。

+0

我正在使用1.6.0_14。現在我已經升級到1.6.0_16,但結果是一樣的。 – asalamon74 2009-08-28 13:36:38