0

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Jake
  • 2,877
  • 8
  • 43
  • 62
  • 1
    possible duplicate of [XML File with local copy of XML Schema](http://stackoverflow.com/questions/3053529/xml-file-with-local-copy-of-xml-schema) – Don Roby Nov 26 '11 at 20:17
  • So YourSchemaDefinition.xsd is actually a URL? One possibility is an "entity resolver" https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file/41225329#41225329 – rogerdpack Jan 04 '18 at 22:52
  • I have tried to answer a similar question here https://stackoverflow.com/questions/44996345 – jschnasse Jan 26 '18 at 10:35

2 Answers2

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.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Bhaskar
  • 7,443
  • 5
  • 39
  • 51
0

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.

Community
  • 1
  • 1
Vincent Biragnet
  • 2,950
  • 15
  • 22