how to use jdk 1.5 & dtd to validate xml file

Z

zero

Hi,

I'm wondering, JDK5 brights with xml parser, validator, etc, but how
can I use its package (or other like web-service packages) to validate
a xml file by a dtd file, before let SAX proceed?

I know an example in SUN's web
(http://java.sun.com/developer/technicalArticles/xml/validationxpath/)

, but it's using xml schema instead of dtd to validate.

Any help?

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse("myfile.xml", new MyDefaultHandler());

where MyDefaultHandler extends DefaultHandler. This code will
automatically validate the xml file if a DTD declaration is present.

packages used are not in javax.xml but org.xml.sax.
 
J

John_Woo

Thanks for the info, but when I tried

t.dtd
<!ELEMENT c (trans*) >
<!ATTLIST c >
<!ELEMENT trans (EMPTY)>
<!ATTLIST trans type CDATA #FIXED "7" >

t.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE c SYSTEM "t.dtd">
<c>
<trans type="9" />
</c>

it's obviously that value 9 didn't match value 7 defined in dtd,
but running the code below

javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();

factory.setValidating(true);
javax.xml.parsers.SAXParser saxParser = factory.newSAXParser();
saxParser.parse("t.xml", new My...());


there was no exception found.

Can u test it?

John
 
Z

zero

Thanks for the info, but when I tried

t.dtd
<!ELEMENT c (trans*) >
<!ATTLIST c >
<!ELEMENT trans (EMPTY)>
<!ATTLIST trans type CDATA #FIXED "7" >

t.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE c SYSTEM "t.dtd">
<c>
<trans type="9" />
</c>

it's obviously that value 9 didn't match value 7 defined in dtd,
but running the code below

javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();

factory.setValidating(true);
javax.xml.parsers.SAXParser saxParser = factory.newSAXParser();
saxParser.parse("t.xml", new My...());


there was no exception found.

Can u test it?

John

Validation errors are nonfatal errors, and are ignored by the
ErrorHandler implementation in DefaultHandler. To throw an exception
when a validation error occurs, you need to override the error
(SAXParseException) and/or warning(SAXParseException) methods.

public void error(SAXParseException e)
throws SAXParseException
{
throw e;
}

public void warning(SAXParseException e)
throws SAXParseException
{
throw e;
}

See the JAXP tutorial at
http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top