How to parse an XML as per dtd in java

How to parse an XML as per dtd in java

Please help to tell me a logic to parse an xml as per mentioned dtd inside xml. I've used SAX and DOM both but that only check for well formed xml tags but don't validate as per DTD. please help

View Answers

December 26, 2011 at 4:28 PM


December 26, 2011 at 7:04 PM

Many Thanks for your help, I've changed little in code and found minimized code for any dtd mentioned in xml. please advice for my below commented lines.

public boolean ParseXML(String filename)

        {
String DTD_PATH = c:/dtd/;

          valid = true;  
          try{
              DocumentBuilderFactory factory = 
              DocumentBuilderFactory.newInstance();
              factory.setValidating(true);
              DocumentBuilder builder = factory.newDocumentBuilder();
                  builder.setErrorHandler(new org.xml.sax.ErrorHandler() 
                  {
                  //Ignore the fatal errors
                      public void fatalError(SAXParseException exception)
                       throws SAXException { }
                      //Validation errors 
                      public void error(SAXParseException e)
                          throws SAXParseException {
                          System.out.println("Error at " +e.getLineNumber() + " line.");
                          m.log.info(this,"PARSING ERROR at line : "+e.getColumnNumber()+" : "+e.getMessage());
                          System.out.println(e.getMessage());
                          valid = false;
                          }
                      //Show warnings
                      public void warning(SAXParseException err)
                      throws SAXParseException{
                        m.log.info(this,"PARSING ERROR at line : "+err.getColumnNumber()+" : "+err.getMessage());
                      System.out.println(err.getMessage());
                      valid = false;
                      //System.exit(0);
                      }
                  });                 
              Document xmlDocument = builder.parse(new FileInputStream(filename),DTD_PATH);

//Please tell me the use of below commented lines since now this code can run on any mentioned dtd in xml.            
/*DOMSource source = new DOMSource(xmlDocument);                          
              StreamResult result = new StreamResult(System.out);
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer transformer = tf.newTransformer();
              transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "c:/dtd/EMC-UPDATE.dtd");
              transformer.transform(source, result);              */

              }
              catch (Exception e) {
              System.out.println("ERROR :: "+e.getMessage());
              m.log.info(this,"ERROR : "+m.ctool.getException(e));
              return false;
              }
              return valid;
          }

December 26, 2011 at 7:05 PM

Many Thanks for your help, I've changed little in code and found minimized code for any dtd mentioned in xml. please advice for my below commented lines.

public boolean ParseXML(String filename)

        {
String DTD_PATH = c:/dtd/;

          valid = true;  
          try{
              DocumentBuilderFactory factory = 
              DocumentBuilderFactory.newInstance();
              factory.setValidating(true);
              DocumentBuilder builder = factory.newDocumentBuilder();
                  builder.setErrorHandler(new org.xml.sax.ErrorHandler() 
                  {
                  //Ignore the fatal errors
                      public void fatalError(SAXParseException exception)
                       throws SAXException { }
                      //Validation errors 
                      public void error(SAXParseException e)
                          throws SAXParseException {
                          System.out.println("Error at " +e.getLineNumber() + " line.");
                          m.log.info(this,"PARSING ERROR at line : "+e.getColumnNumber()+" : "+e.getMessage());
                          System.out.println(e.getMessage());
                          valid = false;
                          }
                      //Show warnings
                      public void warning(SAXParseException err)
                      throws SAXParseException{
                        m.log.info(this,"PARSING ERROR at line : "+err.getColumnNumber()+" : "+err.getMessage());
                      System.out.println(err.getMessage());
                      valid = false;
                      //System.exit(0);
                      }
                  });                 
              Document xmlDocument = builder.parse(new FileInputStream(filename),DTD_PATH);

//Please tell me the use of below commented lines since now this code can run on any mentioned dtd in xml.            
/*DOMSource source = new DOMSource(xmlDocument);                          
              StreamResult result = new StreamResult(System.out);
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer transformer = tf.newTransformer();
              transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "c:/dtd/EMC-UPDATE.dtd");
              transformer.transform(source, result);              */

              }
              catch (Exception e) {
              System.out.println("ERROR :: "+e.getMessage());
              m.log.info(this,"ERROR : "+m.ctool.getException(e));
              return false;
              }
              return valid;
          }









Related Tutorials/Questions & Answers:
How to parse an XML as per dtd in java
How to parse an XML as per dtd in java  Please help to tell me a logic to parse an xml as per mentioned dtd inside xml. I've used SAX and DOM both but that only check for well formed xml tags but don't validate as per DTD. please
XML DTD
XML DTD  What is DTD in xml file ?   A DTD (Document Type Definition) defines the structure and building blocks of a xml document. It can be also written inside the xml document
Advertisements
how to parse xml in j2me tutorial
how to parse xml in j2me tutorial   i want to parse xml file in j2me wireless toolkit.i saw ur examples & source code for parsing xml file in j2me & i try to execute same example on my pc i some how manage to run
Java code to parse xml - Java Beginners
/GetData.shtml The example explains how to parse a xml document. Thanks...Java code to parse xml   TL1 10.50.26.98... to parse the code and get the values from
Problem with external DTD - XML
Problem with external DTD  Hi, This class generate an XML file.But while I am running that generated xml file its giving error as can not locate... classes. OutputFormat of = new OutputFormat("XML","ISO-8859-1",true); of.setIndent
DTD - XML Constituent
DTD - XML Constituent       The constituent components of XML DTD Documents.  DTDs are made up... Elements are the main constituent components of both XML documents.ADS_TO_REPLACE_2
parse xml
; </STATE> How to parse the above xml. please help me   Here is a code that parses an xml file using DOM Parser. import org.w3c.dom.*; import...parse xml   <STATES> <STATE sname="AndhraPradesh" >
How to parse the attributes from XML using KXML parser in j2me
How to parse the attributes from XML using KXML parser in j2me  Dear Sir, I have doubt in How to parse the attributes from XML using KXML parser in j2me ..I parse the dge name value..but i didn't do parsing the attributes
XML Validate DTD
. Description of program:ADS_TO_REPLACE_1 Validating a XML file against a DTD needs a xml file and its DTD document. First of all construct a well-formed xml file along with a DTD file . This DTD file defines all elements to keep in the xml
Java - How to read a string line per line
Java - How to read a string line per line  Java - How to read a string line per line I am trying to find the tutorial for reading the String line... to read the big String line per line? Is there any API available in Java
how to parse xml document which contains elements with namespace using JDOM - XML
is inside so how can i parse this xml using JDOM,java. Thanks Shree  Hi...how to parse xml document which contains elements with namespace using JDOM  Hello, I am parsing XML file ,which has structure like
DTD
DTD   hello, what is DTD? define DTD.   hii,ADS_TO_REPLACE_1 DTD stands for Document Type definition. DTD is a just like a rule book for an XML documents. Once DTD is ready, you can create number of XML documents
XML validation against a dtd -refering http://www.w3.org/1999/xmlschema
XML validation against a dtd -refering  hi i have an issue in validating an xml against dtd .As the currently used schema is http..." old version is there any solution to validate my xml against the dtd i have
How to parse the attributes values from XML using KXML parser in j2me
How to parse the attributes values from XML using KXML parser in j2me  hai team, i did xml parsing from serverside...i got a resultant value from xml,but here tag value name only came from parsing attribute name cant come
Validating XML document with a DTD
Validating XML document with a DTD If an xml document is well formed i.e.... an XML document valid it must be validated, or verified, against a DTD. DTD... in dtd. If your xml file defines the dtd name to ensure the validity of the file
ModuleNotFoundError: No module named 'parse-landsat-xml'
named 'parse-landsat-xml' How to remove the ModuleNotFoundError: No module named 'parse-landsat-xml' error? Thanks   Hi, In your...ModuleNotFoundError: No module named 'parse-landsat-xml'  Hi, My
XML Schema
: #FFFFFF; } XML Schema An XML Schema defines how to structure an XML document and it can be used in place of DTD. XML Schema is based on XML. XML Schema... xml editor can be used to edit xml schema 12 Xml Parser can be used to parse
how do you parse by reference in java(with JGrasp)
how do you parse by reference in java(with JGrasp)  i am a 1st year beginner in java programming(GR 10) at hillcrest High School in south Africa My question is how do you parse by reference in java(with JGrasp) please help me i
Introduction to DTD's
Introduction to DTD's To validate an xml document there should be some set... and attributes. DTD specifies that an xml can contain what elements... with XML document DTD appears near the start of the xml document. Declaration
Creating a DTD
definition (DTD) is used to validate XML files that reference the DTD file... etc for any XML file and defines constraints for how each element, attribute etc may be used within of any XML files that reference the DTD file. DTDs
Introduction to XML - DTD
Introduction to  XML - DTD           Introduction to XML XML is a cross... Type Definition (DTD), XML Schema to describe the data. Hence it is self
DOM Parser Example to Parse A DOM Document
DOM Parser Example to Parse A DOM Document In this tutorial, we will discuss about how to parse(retrieve data) DOM Document. The XML DOM views an XML... : 27  Download the XML Code Download the JAVA code/a>ADS
parse map in java
parse map in java  What is a Parser? Can you give the source code to parse map in Java
XML Validation
; XML with correct syntax is Well Formed XML. XML validated against a DTD... Type Definition (DTD) or a XML Schema . The following xml document is validated...;/Body> </E-mail XML DTD A DTD defines the legal elements
Java XML Parsing Using DOM
Java XML Parsing Using SAX To Parse XML document using SAX parser method you need to follow the following steps. Consider the following XML file... = saxParserFactory.newSAXParser(); // Parsing XML Document by calling parse
Java XML Parsing Using SAX
Java XML Parsing Using SAX To Parse XML document using SAX parser method you need to follow the following steps. Consider the following XML file... = saxParserFactory.newSAXParser(); // Parsing XML Document by calling parse
Java APIs for XML Processing (JAXP)
Java APIs for XML Processing (JAXP)       JAXP (Java APIs for XML Processing) enables applications to parse, transform, validate and query XML documents using API. This API
Java APIs for XML Processing (JAXP)
Java APIs for XML Processing (JAXP)       JAXP (Java APIs for XML Processing) enables applications to parse, transform, validate and query XML documents using API. This API
How to parse data in JSON format
How to parse data in JSON format  Hi, I want to parse following json string in Python and get values from it. user = {"user":"testuser", "password":"testpass", "isactive":"Yes"} How to parse data in JSON format? Thanks
HOW TO PARSE FILE WITH SEVERAL DELIMITERS AND LINE FEEDERS - Java Beginners
HOW TO PARSE FILE WITH SEVERAL DELIMITERS AND LINE FEEDERS  Hi All i need to parse a file of this format,such that i can get/fetch the values present between the tags by avoiding linefeeds or "/n",carriage return 0r "/r
how to update xml from java - XML
how to update xml from java  hi, Im new to xml parsing and dont know much about. I need to modify the attribute val of a tag in a complex xml file by using java code tell me the procedure. Thanks in advance.   hi
how to get this xml syntx in java??????
how to get this xml syntx in java??????  how to get this xml syntx in java?????? < comp xlink:type="new" xlink:actuate="onload"/>
how to get this xml syntx in java??????
how to get this xml syntx in java??????   how to get this xml syntx in java?????? < comp xlink:type="new" xlink:actuate="onload"/>
How to display mysql database records as per clock timing?
How to display mysql database records as per clock timing?  I want to display database records as per clock timing
how to write java data - XML
how to write java data  how to write data to xml file  Hi friend, Read for more information, http://www.roseindia.net/xml/dom/ Thanks
How to write to xml file in Java?
How to write to xml file in Java?  Hi Friends, Can anyone help me how to write in xml file in Java programming. Please fill free to give example or reference website for getting example.   Hi, To write in xml file
Use of <x:parse> tag of JSTL
;    In this section we will learn how to use <x:parse> tag of  Xml tag library of Jstl. This tag is used to parse the specified xml document. Standard Syntax : <%@ taglib prefix="x" uri="
Formatting number as per specific locale in java
Formatting number as per specific locale in java  Hi, I am trying to print the number as per locale. I tried below, but it still prints in English...(Locale.getDefault()); //returns zh. //format the number as per locale -->
how to create xml schema from xml doc using java
how to create xml schema from xml doc using java  i want to create xml schema from xml document programatically using java... am using Netbeans IDE 7.0 i hav created the xml document for a table of data from Database... now i
how to parse a csv file using standard libraries?
how to parse a csv file using standard libraries?  hie i am a beginner in java i want to parse a csv file using any standard libraries i want to know how the libraries are imported and used in eclipse thanks in advance
In data structure in java how to parse the given string and counts the member of character that match the given data?
In data structure in java how to parse the given string and counts the member of character that match the given data?  Design a parser that parse the given string and counts the member of character that match the given data.using
how to read values from java in xml?
how to read values from java in xml?  how to read values from java in xml
How to pretty print XML from Java?
How to pretty print XML from Java?  How to pretty print XML from Java
Processing XML with Java
(parse, validate, transform and query) xml documents in java based applications...; } Processing XML with Java XML is cross-platform software, hardware... according to the defined rules in DTD or XML schema then the document is said
Retrieving Data From the XML file
is only geared towards showing how to construct a Java object from an XML document...;     In this example we will examine how to parse... create a DocumentBuilder object to parse an org.w3c.dom.Document from XML. Save
Hibernate 5 configuration dtd
. Following hibernate.cfg file shows how to include Hibernate 5 dtd correctly...Hibernate 5 configuration dtd Example In Hibernate 5 dtd is different from previous version of Hibernate. Hibernate dtd comes included with the Hibernate
how to convert text file to xml file in java. - XML
how to convert text file to xml file in java.  Hi all, I m... the no of record(i.e no of different line of information)to a xml file through java...://www.roseindia.net/java/java-conversion/TextToXML.shtml Hope that it will be helpful
how to write in xml? - XML
how to write in xml?  can anybody give the code how to write in xml...(new InputStreamReader(System.in)); System.out.print("Enter XML file name...().newTransformer(); // Output Types (text/xml/html
to retrive e mails as per user name - Java Beginners
to retrive e mails as per user name  hi friends, how to retrive e mails as per user "user name " for ex: class Mail{ private String subject.../reading-message-using-java-mail.shtml Thanks
XML and swings - Java Beginners
XML and swings  I have an xml file where all the contents that should be present in the tabbed pane are there. i would like to know how to parse the xml such that, whenever it reads the component type as label, it should create

Ads