2

我有这个 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)));
4

0 回答 0