validating a schema file in local location with saxparser

廉价感情. 提交于 2019-12-25 09:43:14

问题


I was looking at http://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPSAX9.html.

You can associate the xml file with a schema with 2 ways, in the app or in the xml document. In the app you call

saxParser.setProperty(JAXP_SCHEMA_SOURCE,
    new File(schemaSource)); 

in the xml you add this

<documentRoot
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation='YourSchemaDefinition.xsd'
>

The problem is that both locations for the .xsd file are URL strings. The .xsd file i have is a local copy. Is there a way to specify the location? maybe as an input stream?


回答1:


You can set the schema directly on the SAX Parser factory.

 SAXParserFactory factory = SAXParserFactory.newInstance();
 SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 Schema sc = schemafactory.newSchema(new File("path to xsd file"));
 factory.setSchema(sc);

 SAXParser parser = factory.newSAXParser();
 parser.parse(file, handler);

The xsd location in the xml file can also be relative to the xml file, so if your xsd is present along with the xml file locally then your current xml file should work.




回答2:


I assume you're in java. If the schema is in the classpath, you can probably use this post to get it : URL to load resources from the classpath in Java

Having the schemaLocation in instance can be hard to handle if you receive the XML file from a third party. The schemaLocation may be already defined in the XML and may lead to a wrong schema (or to nothing at all). If you want to add it programmatically, you will have to change integrity of data before validation, it can be risky. For validation, IMO, better trust your local copy.



来源:https://stackoverflow.com/questions/8281227/validating-a-schema-file-in-local-location-with-saxparser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!