创建Schema对象Java的问题

时间:2013-06-25 08:57:37

标签: java xml xsd schema

我有这个xsd:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="shiporder">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="orderperson" type="xsd:string"/>
      <xsd:element name="shipto">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="name" type="xsd:string"/>
            <xsd:element name="address" type="xsd:string"/>
            <xsd:element name="city" type="xsd:string"/>
            <xsd:element name="country" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
      <xsd:element name="item" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="title" type="xsd:string"/>
            <xsd:element name="note" type="xsd:string" minOccurs="0"/>
            <xsd:element name="quantity" type="xsd:positiveInteger"/>
            <xsd:element name="price" type="xsd:decimal"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
    <xsd:attribute name="orderid" type="xsd:string" use="required"/>
  </xsd:complexType>
</xsd:element>

</xsd:schema>

这是创建架构的代码:

String xsd = "..."
SchemaFactory schemaFactory = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {
        Schema schema = schemaFactory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
    } catch (SAXException e) {
        System.out.println("Reason: " + e.getLocalizedMessage());
    } catch (IOException e) {
        System.out.println("Reason: " + e.getLocalizedMessage());
    }

我在创建新架构实例时收到此错误:

SCHEMA : schema_reference.4: Failed to read schema document '...', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

字符串xsd表示上面发布的xsd文件。

我该如何解决这个问题?任何的想法?建议?

编辑:我解决替换此行:

Schema schema = schemaFactory.newSchema(new StreamSource(xsd));

用这个:

Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(xsd)));

0 个答案:

没有答案