我有与Java XML验证的问题。

我有以下的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是两个有效?

有帮助吗?

解决方案

尝试把attributeFormDefault = “合格” 在你的XSD。这不应该有所作为,但它是一个快速测试。

另外:你不设置你的DocumentBuilder是名称空间感知。这当然会打破验证,但它会1.5下破裂以及1.6。

和作为一般性评论,在解析时验证是比较有用的,因为你可以看到,未通过验证的内容的行号。下面的代码来做到这一点(schema是先前创建的):

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

其他提示

我会说这是Java 6中的错误,您可以随时把XSI中的任何元素的属性。

这是非常类似于此错误,

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

尝试修复6u14。这极有可能会解决你的了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top