java中的XMLStreamReader到StreamSource

时间:2016-12-19 06:53:58

标签: java xml xsd-validation

我想将XMLStreamReader对象转换为StreamSource对象,以便我可以应用XSD验证。任何人都可以帮我转换它。

public XMLStreamReader getStreamReader(InputStream inputStream) {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        return new XmlStreamReaderDelegate(xif.createXMLStreamReader(inputStream, "UTF-8"));
    } catch (XMLStreamException e) {
        //logger.info(XmlValidatorSettings.class,e.getMessage(),e.getMessage());
        throw new UnmarshallingException(e);
    }
}

我需要调用此方法来针对XSD验证XML。

public List<SAXParseException> validateSrcXmlAgainstSchema(Source xmlFile, String schemaFilePath) throws SAXException, IOException {
    List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new File(schemaFilePath));
    // logger.debug("Schema Initialised for Schema located in : " + schemaFilePath);
    XmlValidationExceptionHandler validationErrorHandler = new XmlValidationExceptionHandler();
    Validator validator = schema.newValidator();
    validator.setErrorHandler(validationErrorHandler);
    // logger.debug("START - validate xml against schema ");
    validator.validate(xmlFile);
    // logger.debug("END - validate xml against schema ");
    exceptions = validationErrorHandler.getExceptionList();
    return exceptions;
    }

XmlStreamReaderDelegate类用于避免XML区分大小写的问题。

public class XmlStreamReaderDelegate extends StreamReaderDelegate {

public XmlStreamReaderDelegate(XMLStreamReader xsr) {
    super(xsr);
}

@Override
public String getAttributeLocalName(int index) {
    return super.getAttributeLocalName(index).toLowerCase().intern();
}

@Override
public String getLocalName() {
    return super.getLocalName().toLowerCase().intern();
}

}

0 个答案:

没有答案