Validating XML documents against a DTD

Guys I am new to XML and I have this requirement to validate a XML document against a DTD.This validation has to be done through my java application.In short , a user enters a XML data thru a JSP form ,and moment he presses the SAVE button my java program should validate the XML data against a DTD and then display any error or else save the data into an Oracle table.
I was wondering lot of program/utitlities must be available out there which will do the validation for me ,rather than me re-inventing the wheel.
Please advice.
Thanks
Manohar.

You should go through this to learn more on XML with Java :
http://www.onjava.com/pub/a/onjava/excerpt/learnjava_23/index1.html
You can check following how to to parse XML doc against a schema
http://otn.oracle.com/sample_code/tech/java/codesnippet/xdk/SchemaValidation/SchemaValidation.html
You should also look at chapter 4 of following doc for parsing XML using java :
http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96621/toc.htm
Chandar

Similar Messages

  • Not able to validate the xml document against DTD using SAX

    Hi ,
    i am not able to validate xml document against its DTD using SAX parser even after setting setValidating = true. even if the file is not correct according to DTD , it is not throwing any exception. what could be the reason.? please help..
    kranthi
    this is the code sample i used.
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
         try {
    factory.newSAXParser().parse(new File("sample.xml"), handler);
         } catch (SAXException e) {
         e.printStackTrace();                         System.exit(2);
         } catch (ParserConfigurationException e) {
    e.printStackTrace();
    }

    Hi karthik
    Thanks for your response
    Actually iam a beginner in java coding hence struggling to come up with the things
    I tried putting your code and onserver side i see it is returning 09:12:17,234 INFO [STDOUT] [root: null]
    actually the same program i wrote in java
    and the same method i was calling from the main
    and it is working fine and the xml document is getting displayed one important thing to be noted here is that the factory.newDocumentBuilder().parse(new File(filename));is returing XmlDocument
    and the printing takes place
    but the in same method public static Document parseXMLFile(String filename, boolean b) in servlet
    the line factory.newDocumentBuilder().parse(new File(filename)); is returning DeferredDocumentImpl
    and this creating problem , had it returned XmlDocument
    i would have printed the elements one one
    but as it is returning deferredimpl
    iam unable to print the elements
    could you please tell me why factory.newDocumentBuilder().parse(new File(filename)); is returning DeferredDocumentImpl
    in servlets but in plain java pogram it is returing XmlDocument
    Thanks
    Bhanu

  • Error: No valid XML document received*_

    Hi All,
    We are connecting our CCMS system to NetWeaver J2EE engine on which E-Sourcing is running.
    For this we registered java component and hosts in cen.
    But we are getting error as : No valid XML document received
    Please can anyone tell me how to overcome this error.
    Thank you .
    Regards
    Mahesh

    Hi,
    Please re-read the answer from Marc carefully.  He was in the exact same situation as yours: 
    - Monitored system: NW CE 7.1
    - CEN: NW 7.01 (same as NW 7.0 EhP1)
    The link you posted is for CEN with NW 7.3 and monitored systems from NW 7.02 (and up).  Read the paragraph below the Caution sign:
    If you want to centrally monitor any system with a central monitoring system with release SAP NetWeaver 7.0, this procedure is not applicable. In this case, follow the procedure described in the newest Monitoring Setup Guide for SAP NetWeaver 7.0 instead. You can obtain the Monitoring Setup Guide at the Internet address service.sap.com/operationsnw70 in the Monitoring area.
    You should look for (and follow) the right Monitoring Setup Guide as mentioned.
    Regards,
    Dao
    Edited by: Dao Ha on Sep 19, 2011 10:38 AM

  • Creating an XML document from a DTD in Java

    Hi All,
    I need help on the following requirement very badly. Pls help me.
    I have a requirement to implement with java and XML. I am quit new to XML.Can any of you pls help me.
    I have a DTD file. I need to generate XML document from it using java code. I have to use DTD as a template to generate my XML document.
    After going through WEB sites, I understtod that, we have to user Java API JAXB for my requirement. But I could not find JAXB.jar anywhere.
    I need to know the following inforamtion ....
    1. Is my understanding of using JAXB for my requirement is correct?
    2. Where can I get JAXB.jar?
    3. What are the steps to create XML document from a DTD in Java?
    If can give me a sample code for this would help me a lot.
    Pls pls reply me. Your help is greatly appreciated.
    Thanks in Advance.
    Regards,
    Gayathri.

    hi Gayathri,
    iam currently working in the same field.
    firs download jaxb from this link:
    http://java.sun.com/xml/downloads/jaxb.html
    first u need to marshall it.
    cheers
    shashi

  • How to use Xerces to validate an XML file against a DTD

    Hi, can anybody tell me how to use Xerces to validate an XML file against a DTD. its urgent. post some sample code. it would be helpful for my project. isupposed to use SAX parser(Xerces)
    Thanx in advance

    Come on, I googled "xerces validate" and the first link is the Xerces FAQ:
    http://xerces.apache.org/xerces-j/faq-general.html
    And of course "how to validate" is a Xerces FAQ. Help yourself by doing a little research instead of waiting for other people.

  • No valid XML document received

    Hi All,
    We are connecting our CCMS system to NetWeaver J2EE engine on which E-Sourcing is running.
    For this we registered java component and hosts in cen.
    But we are getting error as : No valid XML document received
    Please can anyone tell me how to overcome this error.
    Thank you .
    Regards
    Mahesh

    Hi,
    Please re-read the answer from Marc carefully.  He was in the exact same situation as yours: 
    - Monitored system: NW CE 7.1
    - CEN: NW 7.01 (same as NW 7.0 EhP1)
    The link you posted is for CEN with NW 7.3 and monitored systems from NW 7.02 (and up).  Read the paragraph below the Caution sign:
    If you want to centrally monitor any system with a central monitoring system with release SAP NetWeaver 7.0, this procedure is not applicable. In this case, follow the procedure described in the newest Monitoring Setup Guide for SAP NetWeaver 7.0 instead. You can obtain the Monitoring Setup Guide at the Internet address service.sap.com/operationsnw70 in the Monitoring area.
    You should look for (and follow) the right Monitoring Setup Guide as mentioned.
    Regards,
    Dao
    Edited by: Dao Ha on Sep 19, 2011 10:38 AM

  • Relax NG - Validating a  document against it's schema

    Hi
    I am trying to work out how to validate an XML document against a Relax NG schema. There doesn't appear to be much support for Relax NG, and I am not quite sure what tools to use or how to do it, I am new to XML.
    Can anyone suggest how I would go about doing this?
    Regards,
    Kim

    You could use this for Java 1.4:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                           "http://www.w3.org/2001/XMLSchema");
    factory.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                           "test.xsd");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new TOXSDErrorHandler(System.err));
    Document document = builder.parse(fileHandler);

  • URGENT---Validating XML file against DTD

    I have a XML & DTD file.I want to validate that xml file against the specified DTD without using any editor.Through program how can i validate?Pl. help me.It's URGENT.

    >
    and i recieved ORA-31001: Invalid resource handle or path name "/testdtd.dtd"
    when the DBMS_XMLPARSER.parseClob( PARSER , v_xml ); is executed
    i removed the <!DOCTYPE family SYSTEM "testdtd.dtd"> from the XML file
    the procedures worked , but not sure if really validated against the DTD file>
    you have to load your DTD into XDB repository.
    <a href ="http://forums.oracle.com/forums/thread.jspa?threadID=416366">How do I use DTD's with XML DB ?
    Ants

  • Validating an XML document using external DTD?

    Hi,
    I want to validate an XML file using external DTD with SAX parser.
    How can I validate an XML file with external DTD.
    Thanks in Advance,
    Mahendra

    I dont think we can set a DTD file throug java while
    parsing an XML.I've done it with an XML schema though. Can you use that instead? For schemas you do something like:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource",
                                       schemaUrl );where schemaUrl in this case would be something like file:///usr/local/whatever.xsd

  • Validating XML document in Workshop 8.1

    Hi,
    I am new to Workshop. I have little experience with SAX or DOM. I found them
    very confusing.
    I am hoping Workshop 8.1 will provide a more user friendly solution. For a web
    application, on
    the client side, can Workshop validate an XML document, which is created from
    user entries on
    a browser form (Inquiry phase), against a predefined schema? Upon sucessful validation,
    the
    client invokes the web service which returns the result of the inquiry. Upon
    receiving the result,
    can the client augment the result with additional information from an external
    schema before
    displaying the result on the browser?
    Thanks
    Mike

    Mike,
    XMlbeans would provide with functionality to do what you are trying to do.
    Please refer to the SchemaChoice.jws sample which is shipped with Workshop.
    This sample shows how the document can be validated against a schema.
    Please refer to the following document for more information on this
    http://workshop.bea.com/xmlbeans/docindex.html
    Hope this helps.
    Regards,
    Raj Alagumalai
    WebLogic Workshop Support
    "Michael Wong" <[email protected]> wrote in message
    news:[email protected]..
    >
    Hi,
    I am new to Workshop. I have little experience with SAX or DOM. I foundthem
    very confusing.
    I am hoping Workshop 8.1 will provide a more user friendly solution. Fora web
    application, on
    the client side, can Workshop validate an XML document, which is createdfrom
    user entries on
    a browser form (Inquiry phase), against a predefined schema? Uponsucessful validation,
    the
    client invokes the web service which returns the result of the inquiry.Upon
    receiving the result,
    can the client augment the result with additional information from anexternal
    schema before
    displaying the result on the browser?
    Thanks
    Mike

  • Validating XML, but specify where DTD doc is, at runtime?

    Hi all.
    I've looked through a lot of posts in this forum and still cannot find the solution to this problem, so maybe someone here can help me?
    The problem is this:
    I am using a servlet to read in an ordinary XML document, with a normal <!DOCTYPE declaration and validate it. This works great if the DTD file is either located at a specific location on the web server (ie, somewhere that the webserver already looks at as part of it's enviroment) or if I hard code the location of the DTD in the <!DOCTYPE line in the XML doc.
    I want to be able to tell the validating parser (javax.xml.parser.DocumentBuilder) what the actual path to the DTD is. So that if the <!DOCTYPE tag specifies "mydtd.dtd" as the file, then I can then give the parser the path to that file. Does that make any sense?
    I tried using an EntityResolver class etc, but it doesn't do anything. Here is my code:
    javax.xml.parsers.DocumentBuilderFactory docFact = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    docFact.setValidating(true);
    javax.xml.parsers.DocumentBuilder docBuilder = docFact.newDocumentBuilder();
    MyResolver r = new MyResolver();
    r.resolveEntity(null,"mydtd.dtd");
    docBuilder.setErrorHandler(new ErrorHandler() {
    public void error(SAXParseException e) throws SAXException {
    throw new SAXException(e);
    public void fatalError(SAXParseException e) throws SAXException {
    throw new SAXException(e);
    public void warning(SAXParseException e) {
    docBuilder.setEntityResolver(r);
    docBuilder.parse(new InputSource(ClassLoader.getSystemResourceAsStream("xmltestservlet/myxml.xml")));
    class MyResolver implements EntityResolver {
    public InputSource resolveEntity (String publicId, String systemId)
    java.io.InputStream in = ClassLoader.getSystemResourceAsStream("xmltestservlet/"+systemId);
    return new InputSource(in);
    This is the error message that I get :
    org.xml.sax.SAXParseException: File "file:///d:/iPlanet/Servers/https-mucci/config/mydtd.dtd" not found.
    This is because I dont want to keep my dtd file in this directory! I specified in the entityResolver method that I want the actual DTD file to come from the same location as the class files are held. (They are accessed through the ClassLoader.getSystemResourceAsStream() call).
    Does anyone have any ideas, or has anyone been down this road before?
    Thanks
    P.S The contents of my XML and DTD files are below (both are held in the same package as the class files):
    <?xml version='1.0' encoding='utf-8'?>
    <!-- A SAMPLE set of slides -->
    <!DOCTYPE MYXML SYSTEM "mydtd.dtd">
    <MYXML>
         <ITEM>dfdsf</ITEM>
         <ITEM>dsfsfsdfsd</ITEM>
    </MYXML>
    <?xml version='1.0' encoding='utf-8'?>
    <!ELEMENT MYXML (ITEM+)>
    <!ELEMENT ITEM (#PCDATA)>
    Andy

    The problem lies in your EntityResolver.resolveEntity implementation. The parameter systemId contains the full path of the DTD file. So, the code "xmltestservlet/"+systemId will result in something like this:
    xmltestservlet/file:///d:/iPalnet/etc.
    Thus, the resulting InputSource will be returned as null telling the parser to proceed as normal.
    Try this:
    class MyResolver implements EntityResolver {
        public InputSource resolveEntity (String publicId, String systemId)
            if(systemId != null && systemId.endsWith("mydtd.dtd"))
                java.io.InputStream in = ClassLoader.getSystemResourceAsStream("xmltestservlet/"+"mydtd.dtd");
                return new InputSource(in);
            else return null;
    }BTW, the line "r.resolveEntity(null,"mydtd.dtd");" in your code doesn't do anything. For a working code snippet take a look at this thread:
    http://forums.java.sun.com/thread.jsp?forum=34&thread=153776
    Hope that helps,
    Good luck.

  • Validating xml document in java

    Trying to do subject.
    I'm trying to use xsd from file(schemasource = 1) and from clob (schemasource = 0). I have two xsd schemas common_types.xsd and migom.xsd. second includes first. The problem is that when I'm using common_types schema from file I get error
    ORA-29532: Java call terminated by uncaught Java exception: oracle.xml.parser.v2.XMLParseException: An internal error condition occurred.
    and when I validate xml against only first schema has being read from clob I get success, but when I add second xsd, i get the same error, which says nothing at all.
    create or replace and compile java source named XmlTools AS
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import oracle.sql.CLOB;
    import java.io.IOException;
    import org.xml.sax.SAXException;
    import java.sql.SQLException;
    import java.lang.IllegalArgumentException;
    import oracle.xml.parser.v2.XMLParseException;
    import javax.xml.parsers.ParserConfigurationException;
    import java.io.*;
    public class XmlValidator
    static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
    public static void ValidateDocument(int schemasource, oracle.sql.CLOB schemadoc, oracle.sql.CLOB schemadoc1, oracle.sql.CLOB xmldoc) throws SAXException, IOException, SQLException, ParserConfigurationException, XMLParseException, IllegalArgumentException {
    try
    File myfile = new File(".//XML//common_types.xsd");
    if (myfile.exists())
    Serv.log("ValidateDocument", "file size" + Long.toString(myfile.length()));
    /*else
    Serv.log("ValidateDocument", "file doesn't exists" );
    Serv.log("ValidateDocument", "1" );
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    Serv.log("ValidateDocument", "2" );
    SAXParser saxParser = factory.newSAXParser();
    saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    if (schemasource == 0)
    InputSource schemaIs = new InputSource(schemadoc.getCharacterStream());
    InputSource schemaIs1 = new InputSource(schemadoc1.getCharacterStream());
    InputSource[] schemas = {schemaIs, schemaIs1};
    //saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemaIs);
    saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemas);
    else
    saxParser.setProperty(JAXP_SCHEMA_SOURCE, ".//XML//common_types.xsd");
    XMLReader reader = saxParser.getXMLReader();
    //Получаем входной XML документ
    InputSource documentIs = new InputSource(xmldoc.getCharacterStream());
    Serv.log("ValidateDocument", "3" );
    //Запуск разбора
    reader.parse(documentIs);
    Serv.log("ValidateDocument", "4" );
    documentIs = null;
    /*catch (SAXException e)
    Serv.log("ValidateDocument", "SAXException" );
    Serv.log("ValidateDocument", "document is not valid because ");
    Serv.log("ValidateDocument", e.getMessage());
    throw(e);
    catch (ParserConfigurationException e)
    Serv.log("ValidateDocument", "ParserConfigurationException" );
    throw(e);
    catch (IOException e)
    Serv.log("ValidateDocument", "IOException" );
    throw(e);
    catch (XMLParseException e)
    Serv.log("ValidateDocument", "XMLParseException" );
    Serv.log("ValidateDocument", e.getMessage());
    StackTraceElement[] stack = e.getStackTrace();
    for (int i = 0; i < stack.length; i++)
    Serv.log("stacktrace element no " + Integer.toString(i), "toString: " + stack.toString());
    Serv.log("stacktrace element no " + Integer.toString(i), "file name: " + stack[i].getFileName() + ", class name: " + stack[i].getClassName() + ", method name: " + stack[i].getMethodName() + ", line : " + stack[i].getLineNumber());
    throw(e);
    catch (IllegalArgumentException e)
    Serv.log("ValidateDocument", "IllegalArgumentException" );
    Serv.log("ValidateDocument", e.getMessage());
    throw(e);
    additional information got from java stacktrace:
    file name: XMLError.java, class name: oracle.xml.parser.v2.XMLError, method name: flushErrors1, line : 320 file name: NonValidatingParser.java, class name: oracle.xml.parser.v2.NonValidatingParser, method name: parseDocument, line : 300 file name: XMLParser.java, class name: oracle.xml.parser.v2.XMLParser, method name: parse, line : 200 file name: XMLTOOLS, class name: XmlValidator, method name: ValidateDocument, line : 86
    my oracle version is Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod But my aim is to make it work on all versions starting from 9

    I found another examples of xml document validation in Java, but it seems to me that ORACLE's JVM doesn't include such class as SchemaFactory and class SAXParserFactory doesn't have method setSchema. Is it possible to update JVM installed in Oracle?
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);
    SchemaFactory schemaFactory =
    SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    factory.setSchema(schemaFactory.newSchema(
    new Source[] {new StreamSource("contacts.xsd")}));
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    reader.setErrorHandler(new SimpleErrorHandler());
    reader.parse(new InputSource("document.xml"));

  • Problem validating XMl document

    Hi everyone,
    I'm facing a problem validating a XML document with Apache toolkit under windows XP and eclipse 3.0
    I generate a pair of public/private keys using the RSA algorithm. The keys are of arbitrary length, but satisfying RSA conditions, ie we can encrypt and decrypt.
    I can sign my XML document, but no way to validate it. Validation is only ok when I generate random keys using the KeyPairGenerator.
    Do you think that arbitrary length keys don't allow to validate XML document. And do you have any idea how to solve the problem ( I'm not allowed to generate fixed length keys) ?
    Thansk a lot for your precious help.

    solved!
    urghh...forgot to load th eschema..duh. (must be friday)
    here's the fixed code:
        // parse the xml document (validate the xml string using a schema  file)
        // the xml document does not specified the System ID or location of
        // schema..and use no namespace
        public void parse(HandlerType type, String xmldoc) throws SAXException, IOException {
            File           schema      = schemaMap.get(type);
            DefaultHandler handler     = handlerMap.get(yype);
            XMLReader   reader = XMLReaderFactory.createXMLReader(VENDOR);
            InputSource source = new InputSource(new StringReader(xmldoc));
            reader.setContentHandler(handler);
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            "file:///" + schema.getAbsolutePath());
            reader.parse(source);          
        }

  • XML-Document with extern DTD

    Hello!
    How can the Oracle XML-Parser parse a XML-Document without the
    XML-Declaration. There is no information about the Version and
    the DTD in the XML-Document. Can I use an extern DTD?
    Thanks,
    Peter
    null

    Peter Roemer (guest) wrote:
    : Hello!
    : How can the Oracle XML-Parser parse a XML-Document without the
    : XML-Declaration. There is no information about the Version and
    : the DTD in the XML-Document. Can I use an extern DTD?
    : Thanks,
    : Peter
    Have you tried oracle.xml.parser.v2.XMLParser.setDoctype(DTD)?
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • Validating xml input against schema's registered in database

    Hi,
    We have an application that stores a massive XSD document (with cyclical references between schemas) in a VARCHAR2 column of a table. The XSD is loaded everytime an xml input needs to be parsed. The problem is that the XSD is very huge, and maintaining it is going to be a problem as it continues to grow. I don't beleieve this is the most efficient way of doing this.
    What I would like to do is to register each of the schemas that are part of the large XSD and use the <include schemaLocation/> directive. I have seen tutorials for doing this. Example tutorial at this link:
    http://www.cs.utah.edu/classes/cs5530/oracle/doc/B10501_01/appdev.920/a96620/xdb05obj.htm
    My sole purpose for registering the XSD's is to validate any xml input that is passed in as input to my Java program that is running in the database; I don't want to store the input xml in a table. If the input is successfully validated, my program will continue processing.
    I have seen some Java OTN tutorials which have methods with 2 parameters - xml, and xsd. I want to avoid this approach because in my case, the XSD would already be registered in the database.
    Any tips would be very much appreciated.
    Cheers,
    Rudi

    AN XML Document may be validated with schema registered in database.
    http://download-west.oracle.com/docs/cd/B14117_01/appdev.101/b10790/xdb08tra.htm#sthref843

Maybe you are looking for