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"));

Similar Messages

  • 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

  • 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

  • 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

  • Serializing XML Documents(not Java Serialization)

    Hi,
    Iam looking for a class that can serialize the XML documents.
    Heres the problem in detail:
    - I need to create an XML String from scratch taking data from a database.
    - I created the XML Document adding the childs and attributes.
    - I need an XML string from the document. Iam not exactly sure how to do this. But Apache Xerces package provides an XMLSerializer class where we can convert the document into a string.
    Is there any functionality provided. If so where can i find it.
    Thanks,
    -Rao

    Not sure if this is a bug or not (filing one just in case it is) but the following program demonstrates that with 2.0.2.9 the internal subset is serialized correctly if the document was parsed with validationMode set to true. If set to false only the entities show up in the internal subset.
    package xmlbugs;
    import java.io.*;
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    public class TestSerializeLocalSubset {
    private static final String xml =
    "<?xml version='1.0' encoding='UTF-8'?>"+
    "<!DOCTYPE bar ["+
    "<!ENTITY bar 'baz'>"+
    "<!ELEMENT foo EMPTY >"+
    "<!ELEMENT bar (foo) >"+
    "]>"+
    "<bar><foo/></bar>";
    public static void main(String[] a_ ) throws Exception {
    System.out.println("Test with parser in validation mode = false");
    DOMParser d = new DOMParser();
    d.setPreserveWhitespace(false);
    d.setValidationMode(false);
    d.parse( new StringReader(xml));
    Document x = d.getDocument();
    XMLDocument xx = (XMLDocument) x;
    xx.print(System.out);
    System.out.println("Test with parser in validation mode = true");
    DOMParser d2 = new DOMParser();
    d2.setPreserveWhitespace(false);
    d2.setValidationMode(true);
    d2.parse( new StringReader(xml));
    x = d2.getDocument();
    xx = (XMLDocument) x;
    xx.print(System.out);
    }

  • Reading UTF-7 XML document in Java

    I have an XML document and I want to add PrcessingInstruction to it.
    <?xml version="1.0" encoding="UTF-7" ?>
    <root_element>
    <sections>
    <section_introduction>
    <order-no>108800674</order-no>
    <order-type>219</order-type>
    <created-date>5. november 2008</created-date>
    when trying to parse it like
    File tmpFile = new File("C:\\ProvisioningEventError58412.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    Document doc = factory.newDocumentBuilder().parse(tmpFile);
    System.out.println("end");
    I get an exception on Document doc = factory.newDocumentBuilder().parse(tmpFile);
    org.xml.sax.SAXParseException: Invalid encoding name "UTF-7".
    [Fatal Error] ProvisioningEventError58412.xml:1:40: Invalid encoding name "UTF-7".
    Is it possible to set encoding on DocumentBuilder, so it can work with UTF-7 or is there any other was to parse it for adding ProcessingInstruction. Actually I want to add a CSS/XSL file for formatting the XML File.
    Edited by: aamaam on Jul 15, 2009 5:18 AM

    As you will see from [this Supported Encodings document|http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html], it's Java which doesn't support UTF-7, not just DocumentBuilder.
    So you have a couple of options. You could send the document back to whoever produced it and tell them that you can't process it the way it is. That's a legitimate thing to do because [the XML Recommendation|http://www.w3.org/TR/REC-xml/] only requires parsers to support UTF-8 and UTF-16. Support for other encodings is optional.
    Or you could write your own subclass of InputStreamReader which converts a stream of UTF-7 bytes into a stream of chars, and use that as a Reader which you pass to the parser. Somebody may even have done that already and posted it on the web somewhere.

  • 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);          
        }

  • How to create XML document in Java from scratch ?

    I've downloaded the package generated for my schema.
    Now I'm trying to create a XML Document using the interfaces generated and the
    xmlbeans package. In documentation, all samples start with a call to XmlLoader.load(xmlinput).
    In my case I've no xmlinput, I've only java parameters and i need to produce an
    XML document.
    Could you provide a sample code please ?
    Thanks in advance.

    It looks like you only need to use the xmlText() method from the root of any node
    you want to print out to a file. I used a PrintStream() class and then used the
    ps.print(vpDetails.xmlText()); to save to a file.
    Hope this helps.
    Jerald
    "Eric Vasilik" <[email protected]> wrote:
    >
    To create a new, untyped document:
    XmlObject x = XmlLoader.newInstance();
    To create a new, typed document:
    Map options = new HashMap(
    XmlOptions.DOCUMENT_TYPE,
    CustomerDocument.type );
    CustomerDocument cd = (CustomerDocument) =
    XmlLoader.newInstance( options );
    I have changes pending which will alow you to do this more easily:
    CustomerDocument cd = CustomerDocument.Factory.newInstance();
    - Eric
    "Pascal Fuget" <[email protected]> wrote:
    I've downloaded the package generated for my schema.
    Now I'm trying to create a XML Document using the interfaces generated
    and the
    xmlbeans package. In documentation, all samples start with a call to
    XmlLoader.load(xmlinput).
    In my case I've no xmlinput, I've only java parameters and i need to
    produce an
    XML document.
    Could you provide a sample code please ?
    Thanks in advance.

  • 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

  • How to append child to XML document using Java

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
         <bean name="PinnacleReportsData"
              class="com.hsbc.webapp.report.view.GenericPinnacleReportsViewData"
              singleton="false">
              <property name="headers">
                   <value>Account|Cusip|Description|SecType|Sector|Holding|Price|MarketValue|SettleDate|Yield|SprdUST|AL|CFDur|OAS|ZVolOas|OADur|PrepayDur|VolDur|DV01|DVOAS01|KRDur10Y|PrepayModelCalled|CalcError|CalculationTime</value>
              </property>     
              <property name="noOfRows">
                   <value>20</value>
              </property>     
              <property name="rowdata">
                   <list>
                        <value>AA09b|CMO|8000|8000|62052MAD0|MFPLC_4A 2A 144A||8097|99-27+|5.18|0.25|200|0.00||15||||</value>
                        <value>AA09b|CMO|10000|10000|320277AD8|HASCO 2005 F II-A-2||9958|99-13|5.69|0.13|131|0.02||154|0.000|25|0.001|9864</value>
                        <value>AA09b|CMO|8000|2363|46071LAA8|IMT_03-3G A2||2378|100-01|5.18|0.14|33|0.00||2||||</value>
                        <value>AA09b|CMO|1270|312|40430HDW5|HASCO 2006-O II-A-1||309|99-00|8.98|0.16|5|0.01||3|0.000|1|0.001|296</value>
                        <value>AA09b|CMO|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>
                        <value>AA74b|ABS|8000|8000|62052MAD0|MFPLC_4A 2A 144A||8097|99-27+|5.18|0.25|200|0.00||15||||</value>
                        <value>AA74b|ABS|10000|10000|320277AD8|HASCO 2005 F II-A-2||9958|99-13|5.69|0.13|131|0.02||154|0.000|25|0.001|9864</value>
                        <value>AA74b|ABS|8000|2363|46071LAA8|IMT_03-3G A2||2378|100-01|5.18|0.14|33|0.00||2||||</value>
                        <value>AA74b|ABS|1270|312|40430HDW5|HASCO 2006-O II-A-1||309|99-00|8.98|0.16|5|0.01||3|0.000|1|0.001|296</value>
                        <value>AA74b|ABS|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>
                   </list>
              </property>
         </bean>
    </beans>               hi there i have a XML Document above,and i need to append values to the <list> using java.
    i have string values like
         <value>AA74b|ABS|5000|5000|40430HFQ6|HASCO 2006-O M-3||4583|91-15+|8.99|1.16|534|-0.58|-2|-2644|0.016|712|0.080|367625</value>to add, but failing to navigate to the <list>
    any help?

    1. Read the XML file into a DMO object, walk the DOM to find the list, insert your new entry as a child, write the DOM back to a file.
    2. If the XML is not in a file, but in a string, then you can do the same with string input and output.

  • Getting Node Value of an XML document in JAVA.

    Hi,
    In my application, I have got the exact node that I want by parsing the document, but the node value returned is null as the node is an element and the Java Documentation does specify that it will return null. I would like to know if there in any alternative way by which I can parse the document and get the specified value of the node or element. Kindly Help.

    Well, there are not many mind readers on this forum.
    You do not tell us how you are parsing the document, and so it is difficult determining why the node value is returned as a null.
    There are two main styles of processing XML -- DOM and SAX. Dom (and its variants JDom and I think Dom4J) build a tree structure that is memory-resident. There are ways to walk up and down the tree, and locate arbitrary nodes in the tree.
    The other style is SAX, which is much less intensive from a memroy perspective, but puts more work on you to keep what you want as the data goes flying by.
    So, how are you "parsing the document" and what method is returning a null? That may give someone enough information to guess at your problem.
    Dave Patterson

  • Generic Populating the XML document using Java Class Generator and Reflection

    I am looking for a generic source code in order to convert the data parsed from any tabular text form ( tab delimited for example that maps certain XML Schema created form Database Schema for Oracle.
    I know it is possible to generate XML DTD or XSD from Oracle database table schema by XSU utility from XDK. And also it is possible to create Java source files from an XML DTD or XSD by using XML Clas Generator.
    I believe there must be some generic code that parses tabular text data and converts them to XML format using above mentioned generated Java source files and may be Java reflection mechanism.
    If anyone has any tool or knows any free ware that helps me, I would like to know about it, and I would really appreciate it.

    1. Read the XML file into a DMO object, walk the DOM to find the list, insert your new entry as a child, write the DOM back to a file.
    2. If the XML is not in a file, but in a string, then you can do the same with string input and output.

  • XML document reading in java

    Hello
    Can any one help me to read XML document in JAVA
    Thank u

    I'd use the nanoXML parser because it's small enough to fit easily on a STB.
    Roger

  • Issue in Store XML into Schema generated tables and Validation XML against registered schema.

    Hello friends,
    I am facing some problem when store xml into generated tables from registered schema.
    This is my Schema
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.abc.inf.in/test" targetNamespace="http://www.abc.inf.in/test" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:include schemaLocation="abc.xsd"/>
      <xs:element name="project" type="student">
      <xs:annotation>
      <xs:documentation> This is a Documentation</xs:documentation>
      </xs:annotation>
      </xs:element>
    </xs:schema>
    -- This is my xml document
    <project versao="2.00" xmlns="http://www.abc.inf.in/test">
      <test xmlns="http://www.abc.inf.in/test">
      <intest version="2.00" Id="testabc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  >
      <ide>
      <cUF>35</cUF>
      <cNF>59386422</cNF>
      <natOp>this is post</natOp>
      <indPag>1</indPag>
      <mod>55</mod>
      <serie>1</serie>
      </ide>............
    Not giving full because it's too long.
    1. I Successfully registered Schema into database
    2. Then i generate table from registered Schema
    2. In my java code i validated XML document against Schema and it's successfully validate.
    3. But when i stored this XML into this generated table it's give me error
       Like :
    INSERT INTO XMLTABLE
    VALUES
    (XMLTYPE(bfilename('MYDIR','testabc.xml'),NLS_CHARSET_ID('AL32UTF8')))
    Error report:
    SQL Error: ORA-31061: XDB error: XML event error
    ORA-19202: Error occurred in XML processing
    LSX-00333: literal "94032000" is not valid with respect to the pattern
    And i have to store this xml into this tables so what i have to do ?

    Thanks for your reply odie_63.
    I got this my error solution. My XML document is not well structured based on my registered XML Schema.
    Means In My XML Document there are some invalid value and that not match my schema pattern so it's gives this error
    SQL Error: ORA-31061: XDB error: XML event error
    ORA-19202: Error occurred in XML processing
    LSX-00333: literal "94032000" is not valid with respect to the pattern
    For Solution we have two ways
    1. I have changed this literal "94032000" value in my xml file then save it.
    2.
    - We have to delete this schema then
    - we have to change Schema pattern for particular element
    like :--
    <xs:restriction base="xs:string">
      <xs:whiteSpace value="preserve"/>
      <xs:pattern value="[0-9]{3}"/>
    </xs:restriction>
    - then store xml into database it works..
    Thanks.

  • Checking wellformedness of XML document

    Hello,
    Can anybody tell me how to check the well-formedness of an XML document in JAVA.
    Thanks

    Hi,
    Being "well formed" just means matching start and end tags.
    As far as I know.... all XML parsers check for that.
    If you mean, valid, ie. checking an XML document against a DTD or XML Schema, then here's some source code I had lying around on my machine. Must've downloaded it from somewhere.
    It compiles and runs.
    regards,
    Owen
    // JAXP packages
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import java.util.*;
    import java.io.*;
    public class TestSax extends DefaultHandler
        /** Constants used for JAXP 1.2 */
        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";
        /** A Hashtable with tag names as keys and Integers as values */
        private Hashtable tags;
        // Parser calls this once at the beginning of a document
        public void startDocument() throws SAXException
            tags = new Hashtable();
        // Parser calls this for each element in a document
        public void startElement (String namespaceURI,
                                        String localName,
                                  String qName,
                                  Attributes atts)
                   throws SAXException
            String key = localName;
            Object value = tags.get(key);
            if (value == null)
                // Add a new entry
                tags.put(key, new Integer(1));
            else
                // Get the current count and increment it
                int count = ((Integer)value).intValue();
                count++;
                tags.put(key, new Integer(count));
        // Parser calls this once after parsing a document
        public void endDocument() throws SAXException
            Enumeration e = tags.keys();
            while (e.hasMoreElements())
                String tag = (String)e.nextElement();
                int count = ((Integer)tags.get(tag)).intValue();
                System.out.println("Local Name \"" + tag + "\" occurs " + count + " times");
         * Convert from a filename to a file URL.
        private static String convertToFileURL(String filename)
            // On JDK 1.2 and later, simplify this to:
            // "path = file.toURL().toString()".
            String path = new File(filename).getAbsolutePath();
            if (File.separatorChar != '/')
                path = path.replace(File.separatorChar, '/');
            if (!path.startsWith("/"))
                path = "/" + path;
            return "file:" + path;
        private static void usage()
            System.err.println("Usage: TestXML [-options] <file.xml>");
            System.err.println("       -dtd = DTD validation");
            System.err.println("       -xsd | -xsdss <file.xsd> = W3C XML Schema validation using xsi: hints");
            System.err.println("           in instance document or schema source <file.xsd>");
            System.err.println("       -xsdss <file> = W3C XML Schema validation using schema source <file>");
            System.err.println("       -usage or -help = this message");
            System.exit(1);
        public static void main (String[] args) throws Exception
            String filename = null;
            boolean dtdValidate = false;
            boolean xsdValidate = false;
            String schemaSource = null;
            // Parse arguments
            for (int i = 0; i < args.length; i++)
                if (args.equals("-dtd"))
    dtdValidate = true;
    else if (args[i].equals("-xsd"))
    xsdValidate = true;
    else if (args[i].equals("-xsdss"))
    if (i == args.length - 1)
    usage();
    xsdValidate = true;
    schemaSource = args[++i];
    else if (args[i].equals("-usage"))
    usage();
    else if (args[i].equals("-help"))
    usage();
    else
    filename = args[i];
    // Must be last arg
    if (i != args.length - 1)
    usage();
    if (filename == null)
    usage();
    // There are several ways to parse a document using SAX and JAXP.
    // We show one approach here. The first step is to bootstrap a
    // parser. There are two ways: one is to use only the SAX API, the
    // other is to use the JAXP utility classes in the
    // javax.xml.parsers package. We use the second approach here
    // because at the time of this writing it probably is the most
    // portable solution for a JAXP compatible parser. After
    // bootstrapping a parser/XMLReader, there are several ways to
    // begin a parse. In this example, we use the SAX API.
    // Create a JAXP SAXParserFactory and configure it
    SAXParserFactory spf = SAXParserFactory.newInstance();
    // Set namespaceAware to true to get a parser that corresponds to
    // the default SAX2 namespace feature setting. This is necessary
    // because the default value from JAXP 1.0 was defined to be false.
    spf.setNamespaceAware(true);
    // Validation part 1: set whether validation is on
    spf.setValidating(dtdValidate || xsdValidate);
    // Create a JAXP SAXParser
    SAXParser saxParser = spf.newSAXParser();
    // Validation part 2a: set the schema language if necessary
    if (xsdValidate)
    try
    saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    catch (SAXNotRecognizedException x)
    // This can happen if the parser does not support JAXP 1.2
    System.err.println( "Error: JAXP SAXParser property not recognized: "
                        + JAXP_SCHEMA_LANGUAGE);
    System.err.println("Check to see if parser conforms to JAXP 1.2 spec.");
    System.exit(1);
    // Validation part 2b: Set the schema source, if any. See the JAXP
    // 1.2 maintenance update specification for more complex usages of
    // this feature.
    if (schemaSource != null)
    saxParser.setProperty(JAXP_SCHEMA_SOURCE, new File(schemaSource));
    // Get the encapsulated SAX XMLReader
    XMLReader xmlReader = saxParser.getXMLReader();
    // Set the ContentHandler of the XMLReader
    xmlReader.setContentHandler(new TestSax());
    // Set an ErrorHandler before parsing
    xmlReader.setErrorHandler(new MyErrorHandler(System.err));
    // Tell the XMLReader to parse the XML document
    xmlReader.parse(convertToFileURL(filename));
    // Error handler to report errors and warnings
    private static class MyErrorHandler implements ErrorHandler
    /** Error handler output goes here */
    private PrintStream out;
    MyErrorHandler(PrintStream out)
    this.out = out;
    * Returns a string describing parse exception details
    private String getParseExceptionInfo(SAXParseException spe)
    String systemId = spe.getSystemId();
    if (systemId == null)
    systemId = "null";
    String info = "URI=" + systemId +
    " Line=" + spe.getLineNumber() +
    ": " + spe.getMessage();
    return info;
    // The following methods are standard SAX ErrorHandler methods.
    // See SAX documentation for more info.
    public void warning(SAXParseException spe) throws SAXException
    out.println("Warning: " + getParseExceptionInfo(spe));
    public void error(SAXParseException spe) throws SAXException
    String message = "Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);
    public void fatalError(SAXParseException spe) throws SAXException
    String message = "Fatal Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);

Maybe you are looking for