使用XAS解析器不能使用XSD验证XML

时间:2014-05-15 08:09:34

标签: java xml validation xsd sax

似乎在我的后续xml中验证不成功。

addressbook.xml

<?xml version ="1.0" encoding="UTF-8"?>

<addressbook>
    <address>
        <name>
            <first-name>Samitha</first-name>
            <last-name>Chathuranga</last-name>
            <sasa>dd</sasa>
        </name>
        <street>107 B</street>
        <village>Poramba</village>
        <city>AG</city>
        <postal-code>80300</postal-code>
        <country>Sri Lanka</country>
    </address>
    <address>
        <name>
            <first-name>Hasara</first-name>
            <last-name>Semini</last-name>
        </name>
        <street>32 A</street>
        <village>Dombanwila</village>
        <city>RG</city>
        <postal-code>34300</postal-code>
        <country>Sri Lanka</country>
    </address>

</addressbook>

我已经添加了额外的元素dd来检查它是否被验证到以下XSD,但似乎没有。没有错误消息。因此验证似乎不成功。

addressbook.xsd

<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="addressbook">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="address" maxOccurs="unbounded"/>          
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="address" >
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="name" />
                <xsd:element ref="street" />
                <xsd:element ref="village" />
                <xsd:element ref="city" />
                <xsd:element ref="postal-code" />
                <xsd:element ref="country" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="name">
        <xsd:complexType>
        <xsd:sequence>
            <xsd:element ref="first-name"/>
            <xsd:element ref="last-name"/>
        </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="first-name" type="xsd:string" />
    <xsd:element name="last-name" type="xsd:string" />
    <xsd:element name="street" type="xsd:string" />
    <xsd:element name="village" type="xsd:string" />

    <xsd:element name="city">
        <xsd:simpleType>
            <xsd:restriction base="xsd:string">
                <xsd:length value="2" />
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:element>

    <xsd:element name="postal-code" type="xsd:string" />
    <xsd:element name="country" type="xsd:string" />

</xsd:schema>

它是什么原因?

以下是用于使用SAX进行验证和解析的2个java类。

SAX_XSDValidator.java

//1. Checks for well-formed-ness of the XML with extrnal XML Schema when parsing by SAX Parser.
//2. Validated the XML file with external XML schema Using SAX Parser

// JAXP
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class SAX_XSDValidator {
    public static void main(String[] args) {
        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            // checking for well-formed-ness using SAX.=>This doesn't validate
            // against XSD
            // Turn off validation, and turn on namespaces
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            reader.setErrorHandler(new SimpleErrorHandler());
            reader.parse(new InputSource("src/addressbook.xml"));
            System.out.println("Checked well-formed-ness using SAX ");


            // validating using external schema Using SAX Parser
            // SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource("src/addressbook.xsd") }));
            reader.setErrorHandler(new SimpleErrorHandler());
            reader.parse(new InputSource("src/addressbook.xml"));
            System.out.println("Validation Checked when Parsing with SAX");


            System.out.println("Parsing successful");

        } catch (ParserConfigurationException e) {
            System.out.println("The underlying parser does not support "
                    + " the requested features.");
        } catch (FactoryConfigurationError e) {
            System.out.println("Error occurred obtaining SAX Parser Factory.");
        } catch (Exception e) {
            System.out.println("Caught Exception");
            e.printStackTrace();
        }
    }
}

SimpleErrorHandler.java

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;

public class SimpleErrorHandler implements ErrorHandler {
    public void warning(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void error(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println(e.getMessage());
    }

}

1 个答案:

答案 0 :(得分:1)

您需要创建一个新的SAXParser:您正在更改factory变量,但您的reader仍然使用旧的SAXParser

// checking for well-formed-ness using SAX.
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);

SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();

reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource("src/addressbook.xml"));
System.out.println("Checked well-formed-ness using SAX ");


// validating using external schema Using SAX Parser
factory.setValidating(false); // set validation to false
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource("src/addressbook.xsd") }));

parser = factory.newSAXParser(); // create a new parser
reader = parser.getXMLReader(); // and refresh your reader

reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource("src/addressbook.xml"));
System.out.println("Validation Checked when Parsing with SAX");


System.out.println("Parsing successful");