针对具有include的xsd验证xml

时间:2012-06-07 17:00:22

标签: java xsd xml-parsing xml-validation

我正在尝试针对XSD验证XML,内部引用另一个XSD(使用include语句)。

如,

<xs:include schemaLocation="Schema2.xsd"/>

现在在针对xsd(schema1.xsd)验证我的XML时,例如:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();

        Document document = builder.parse(new InputSource(new StringReader(
                inputXml)));
        TransformerFactory tranFactory = TransformerFactory.newInstance();
        Transformer aTransformer = tranFactory.newTransformer();
        Source src = new DOMSource(document);
        Result xmlFile = new StreamResult(new File("xmlFileName.xml"));
        aTransformer.transform(src, xmlFile);
    } catch (Exception e) {
        // TODO: handle exception
    }

    File xmlFile = new File("xmlFileName.xml");
    SchemaFactory factory1 = SchemaFactory
            .newInstance("http://www.w3.org/2001/XMLSchema");

    File schemaLocation = new File("F:\\Project\\Automation\\XSDs\\schema1.xsd");
    Schema schema = factory1.newSchema(schemaLocation);

    Validator validator = schema.newValidator();

    Source source = new StreamSource(xmlFile);

    try {
        validator.validate(source);
        System.out.println(xmlFile.getName() + " is valid.");
        isXmlValid = true;
    } catch (SAXException ex) {
        System.out.println(xmlFile.getName() + " is not valid because ");
        System.out.println(ex.getMessage());
        isXmlValid = false;
    }

我收到错误,“cvc-datatype-valid.1.2.1:'True'不是'boolean'的有效值。”

这是针对schema1.xsd所引用的schema2.xsd中定义的元素。

如果我做错了,请告诉我。

1 个答案:

答案 0 :(得分:1)

您遇到了案件问题。 'true'是xsd:boolean的有效值,但'True'(显然是XML文档中的内容)不是。

此处的回复(xsd:boolean element type accept "true" but not "True". How can I make it accept it?)提供了一些额外的信息以及基于枚举值的可能的替代解决方案(如果您无法将True更改为true)。