Click here to Skip to main content
15,897,371 members

Need idea for XML validation

ammu23 asked:

Open original thread
Hi,

I wrote java code for xml validation against xsd file.In that if any error in xml it throws the exception.Instead of that i want that program to return result in string like what is the problem.

Java
package com.xmlpack;
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;
public class SampleXmlValidator  {
	public static void main(String args[]) throws SAXException, IOException {
		// Construct a StreamSource from a File.
		Source xmlFile = new StreamSource(new File(
				"D:/SampleXML/sample/src/com/xml/product.xml"));
		// SchemaFactory is a schema compiler. It reads external representations
		// of schemas and prepares them for validation.
		SchemaFactory schemaFactory = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		// This object represents a set of constraints that can be checked/
		// enforced against an XML document.
		Schema schema = schemaFactory.newSchema(new File(
				"D:/SampleXML/sample/src/com/xsd/product.xsd"));
		// A processor that checks an XML document against Schema.
		Validator validator = schema.newValidator();
	
		try {
			validator.validate(xmlFile);
			System.out.println(xmlFile.getSystemId() + " is valid");
		} catch (SAXException e) {
			System.out.println(xmlFile.getSystemId() + " is NOT valid");
			System.out.println("Reason: " + e.getLocalizedMessage());
		}
	}
}



in google search i found that we can use validator.validate(Source,Result) method.
I want to know how to implement the method..
Tags: XML, Java

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900