1

我正在尝试针对 android 中给定的 xsd 文件进行 xml 验证,每次我包含以下行时,应用程序都会意外停止:

SchemaFactory 工厂 = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

这是相关的代码片段:

 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

   File schemaLocation = new File("/sdcard/sep.xsd");
   Schema schema = factory.newSchema(schemaLocation);

   Validator validator = schema.newValidator();

   Source source = new StreamSource("/sdcard/gtp.xml");

    try {          
        validator.validate(source);
    }
    catch (SAXException ex) {
    Toast toast = Toast.makeText(this, "invalid", Toast.LENGTH_SHORT);
    toast.show();
        }  
4

1 回答 1

0

这是解决方案:

File xmlData;
File xmlSchema;
xmlData = new File( xmlDataName );
xmlData = new File( xmlSchemaName );
SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource( xmlSchema );
Source xmlSource = new StreamSource( xmlData );
Schema schema = schemafactory.newSchema( schemaFile );
Validator validator = schema.newValidator();
validator.validate( xmlSource );

但是您需要将 XML 验证库添加到您的项目中。

例如:https ://code.google.com/p/xerces-for-android/ 。

于 2014-08-07T11:31:53.623 回答