SAX Qns

the following codes will print out my whole XML document. Is there any way to print a selected item from the xml file?
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Parse{
     public static void main(String [] args) throws Exception{
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser=factory.newSAXParser();
     parser.parse("Product.xml",new Handler());
class Handler extends DefaultHandler{
     public void startDocument(){
          System.out.println("Start of SAX Parsing");
     public void endDocument(){
          System.out.println("End of SAX Parsing");
     public void startElement(String namespace,String name,String qName,Attributes atts){
     public void endElement(String namespace,String name,String qName){
     public void characters(char [] ch,int start, int length){
          String textData=new String (ch,start,length);
          System.out.print(textData);
<?xml version="1.0" ?>
  <PRODUCT>
  <ITEM>
  <PRODID>P001</PRODID>
  <PRODNAME>Tiga Action Figure #1</PRODNAME>
  <PRODDESC>15 cm Ultraman Figure</PRODDESC>
  <PRICE>7.95</PRICE>
  </ITEM>
  <ITEM>
  <PRODID>P003</PRODID>
  <PRODNAME>Dyna Action Figure #1</PRODNAME>
  <PRODDESC>15 cm Ultraman Figure</PRODDESC>
  <PRICE>7.95</PRICE>
  </ITEM>
  </PRODUCT>

it seems unlikely that that code produced that output, but anywhoo, you would need to put in some if branches in your startElement method, for instance.

Similar Messages

  • Xml-sax

    hi all
    i am getting the following error while running a java program...can anyone help me in setting the sax driver...?
    log:
    java.lang.ClassNotFoundException: org.apache.crimson.parser.XMLReaderImpl
         at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
         at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
         at MySAXApp.main(MySAXApp.java:17)
    Exception in thread "main"
    thanks in advance..!

    log:
    java.lang.ClassNotFoundException:
    org.apache.crimson.parser.XMLReaderImpl
    at
    t
    org.xml.sax.helpers.XMLReaderFactory.createXMLReader(U
    nknown Source)
    at
    t
    org.xml.sax.helpers.XMLReaderFactory.createXMLReader(U
    nknown Source)
         at MySAXApp.main(MySAXApp.java:17)
    Exception in thread "main" That class is found in "rt.jar" in JDK 1.4 onwards. Are you using 1.4 or higher?

  • XML - 0112 Error on parsing using SAX and xml file in InputSource object.

    I need to parse a XML string and extract some information. I have to use SAX parser. I'm converting hte string to InputSource and then trying to parese.
    i'm getting XML-0112 error, my guess is that it is not able to locate DTD file but i tried hardcoding the whole path in DOCTYPE tag.
    i tried doing setSystemId also but no luck.
    null

    Can you post a simple test case to look at?

  • Difference between DOM and SAX

    Difference between DOM and SAX

    a sax parser is event driven meaning it processes the xml as it sees it and then forgets about it.
    you have to implement what you want the parser to do wants it reaches a certain event
    dom on the other hand keeps the whole structure of the message in memory as a tree.
    so there are strengths and weaknesses in both.
    you have to evaluate what you need

  • Is there any possibility to combine XPath with SAX in Java?

    HI Gentlemen,
    I have an XML instance to parse. One solution works with XPath and Document builder. However, the tree in memory is too big so that I can not build it in my storage (8 GB). Does anyone of you know a method where I use an XPath expression (Java) to select a node but with a better parser (e g SAX) which is not so space hungry? Direct access of nodes is obligatory.
    Thanks, kind regards from
    Miklos HERBOLY

    As SAX  parsers do not build a DOM structure and XPath requires a DOM structure to select elements from, XPath is not usable with SAX, but some analysers support setting the XPath expressions to analyse before invoking the SAX parser and provide the result for XPath expressions.
    Refer
    https://code.google.com/p/xpath4sax/

  • Urgent: SAX parser bean is not working in JSP page

    Hi All,
    I have created a bean "ReadAtts" and included into a jsp file using
    "useBean", It is not working. I tried all possibilities. But Failed Plz Help me.
    Below are the details:
    Java Bean: ReadAtts.java
    package sax;
    import java.io.*;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import java.util.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.ParserConfigurationException;
    public class ReadAtts extends DefaultHandler implements java.io.Serializable
         private Vector attNames = new Vector(); //Stores all the att names from the XML
         private Vector attValues = new Vector();
         private Vector att = new Vector();
         private Locator locator;
         private static String start="",end="",QueryString="",QString1="",QString2="";
    private static boolean start_collecting=false;
         public ReadAtts()
         public Vector parse(String filename,String xpath) throws Exception
    QueryString=xpath;
         StringTokenizer QueryString_ST = new StringTokenizer(QueryString,"/");
         int stLen = QueryString_ST.countTokens();
         while(QueryString_ST.hasMoreTokens())
              if((QueryString_ST.countTokens())>1)
              QString1 = QueryString_ST.nextToken();
    else if((QueryString_ST.countTokens())>0)
                   QString2 = QueryString_ST.nextToken();
         SAXParserFactory spf =
    SAXParserFactory.newInstance();
    spf.setValidating(false);
    SAXParser saxParser = spf.newSAXParser();
    // create an XML reader
    XMLReader reader = saxParser.getXMLReader();
    FileReader file = new FileReader(filename);
    // set handler
    reader.setContentHandler(this);
    // call parse on an input source
    reader.parse(new InputSource(file));
         att.add("This is now added");
         //return attNames;
    return att;
    public void setDocumentLocator(Locator locator)
    this.locator = locator;
    public void startDocument() {   }
    public void endDocument() {  }
    public void startPrefixMapping(String prefix, String uri) { }
    public void endPrefixMapping(String prefix) {  }
    /** The opening tag of an element. */
    public void startElement(String namespaceURI, String localName,String qName, Attributes atts)
    start=localName;
    if(start.equals(QString2))
    start_collecting=true; //start collecting nodes
    if(start_collecting)
    if((atts.getLength())>0)
    for(int i=0;i<=(atts.getLength()-1);i++)
    attNames.add((String)atts.getLocalName(i));
    attValues.add((String)atts.getValue(i));
    /** The closing tag of an element. */
    public void endElement(String namespaceURI, String localName, String qName)
    end = localName;
    if(end.equals(QString2))
         start_collecting=false; //stop colelcting nodes
    /** Character data. */
    public void characters(char[] ch, int start, int length) { }
    /** Ignorable whitespace character data. */
    public void ignorableWhitespace(char[] ch, int start, int length){ }
    /** Processing Instruction */
    public void processingInstruction(String target, String data) { }
    /** A skipped entity. */
    public void skippedEntity(String name) { }
    public static void main(String[] args)
    String fname=args[0];
    String Xpath=args[1];
    System.out.println("\n from main() "+(new ReadAtts().parse(fname,Xpath)));
    //System.out.println("\n from main() "+new ReadAtts().attNames());
    //System.out.println("\n from main() "+new ReadAtts().attValues());
    JSP File:
    <%@ page import="sax.*,java.io.*,java.util.*,java.lang.*,java.text.*;" %>
    <jsp:useBean id="p" class="sax.ReadAtts"/>
    Data after Parsing is.....
    <%=p.parse"E:/Log.xml","/acq/service/metrics/system/stackUsage")%>
    Expected Output:
    The jsp file should print all the vector objects from the "ReadAtts" bean
    Actual Output:
    Data after Parsing.......[]
    Thanks for your time.....
    Newton
    Bangalore. INDIA

    the problem is not because of java code insdie jsp page
    I have removed all things but the form and it is still not working
    here is the modified code:
    <!-- add news-->
    <%
    if(request.getParameter("addBTN") != null){
            out.print("addBTN");
    %>
    <!-- end of add news-->
    <form action="" method="post" enctype="multipart/form-data" name="upform" >
      <table width="99%" border="0" align="center" cellpadding="1" cellspacing="1">
        <tr>
          <td colspan="2" align="right" bgcolor="#EAEAEA" class="borderdTable"><p>'6'A) .(1 ,/J/</p></td>
        </tr>
        <tr>
          <td width="87%" align="right"><label>
            <input name="title" type="text" class="rightText" id="title">
          </label></td>
          <td width="13%" align="right">9FH'F 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><textarea name="elm1" cols="50" rows="10" id="elm1" style="direction:rtl" >
              </textarea></td>
          <td align="right">*A'5JD 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input type="file" name="filename" id="filename">
          </label></td>
          <td align="right">5H1)</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input name="addBTN" type="submit" class="btn" id="addBTN" value="  '6'A) .(1 ">
          </label></td>
          <td align="right"> </td>
        </tr>
      </table>
    </form>
    <!-- TinyMCE -->
    <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript">
            tinyMCE.init({
                    mode : "textareas",
                    theme : "simple",
                    directionality : "rtl"
    </script>
    <!--end of TinyMCE -->

  • "Right" way to mix SAX and DOM in app

    I'm writing a standalone desktop application that reads and stores data as XML files. Eventually, it might be converted to use some web services, but it's not a priority right now.
    What I need to do is to use an XML file, which could be large, as kind of a database -- there are many entries, each with a unique identifier, and the application will query the file to find those it needs to match and returns those as objects I'm mapping.
    At the moment, because this is a personal project and I'm using it to learn more technologies, I'm trying to (somewhat artificially) restrict myself to the pure Sun APIs. So far, my investigations have pointed to JAXP (by including Java EE 5 libraries) with StAX (including JAX-WS). Which raises two questions:
    1) To do this "right", do I really need to bundle my app with the entire JaveEE+Metro stack?
    2) Is there a better solution than StAX that's fully Java 5 compliant, even if it means stepping out of the Sun box? I haven't found many references to other solutions that are more recent than 2004. Is parsing XML on an app that has nothing to do with an appserver that uncommon?

    More likely than not, I won't be abstracting to that degree. If the current structure isn't right, I'd update the app instead of storing that kind of information in more files.
    I imagine at this point an example would be more effective. The app is itself more of an inventory browser that can jump around different searches dynamically. As an illustration, imagine that it's an inventory for DVDs. One central file will be your collection (with each entry containing a movie ID, date of purchase, etc). Another file would be more static, a list of DVDs themselves. These entries would contain information about the package itself -- how many discs? What's the title of the package? Which special features does it have? It would also point to an entry in yet another file which would have information about the film, containing biographies of the people listed under the movie credits.
    Basically, I want a flatfile database that I can do joins on that are split up into different files. There are few files (here, one) that will be constantly updated by the user. The others could be modified if needed, but it's not going to be optimized for it. (For example, you could own a DVD that nobody's ever heard of, and put in the info yourself.) Periodically, one or more of the more static files is updated and will be downloaded into the app.
    One of the advantages I see for this is that, in the future, I could with few changes turn this into more of a web service. Instead of pushing changes in those few files, the app would look to a web service for the data it would now find in files on the user's hard drive. But for now, it also has to be one standalone package.
    To answer the question, the file that will most commonly be updated by the user is the one that I don't have problems loading into memory in full. It's the other data that it links to which I want to be able to search and load into objects dynamically. My current implementation is to run the file through SAX and grab the data as it sees it, but it's really ugly. That could very well be how I'm using it and not because I'm trying to shoehorn some functionality into a technique it doesn't fit, but I'd like to find that out. ;)

  • Org.xml.sax.SAXParseException with XML Report Publish

    Anyone see the following error in XML Report Publisher? This happened after I ran Employee W2 XML Interface and ran XML Report Publisher for the output of the PDF output.
    --XDOException
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at oracle.apps.xdo.common.xml.XSLT10gR1.invokeParse(XSLT10gR1.java:570)
         at oracle.apps.xdo.common.xml.XSLT10gR1.transform(XSLT10gR1.java:235)
         at oracle.apps.xdo.common.xml.XSLTWrapper.transform(XSLTWrapper.java:182)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:1044)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:997)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:212)
         at oracle.apps.xdo.template.FOProcessor.createFO(FOProcessor.java:1665)
         at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:975)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.runProcessTemplate(TemplateHelper.java:5936)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3459)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3548)
         at oracle.apps.xdo.oa.cp.JCP4XMLPublisher.runProgram(JCP4XMLPublisher.java:684)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:157)
    Caused by: org.xml.sax.SAXParseException: <Line 268, Column 6>: XML-20109: (Fatal Error) PI with the name 'xml' can occur only in the beginning of the document.
         at oracle.xdo.parser.v2.XMLError.flushErrorHandler(XMLError.java:441)
         at oracle.xdo.parser.v2.XMLError.flushErrors1(XMLError.java:303)
         at oracle.xdo.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:305)
         at oracle.xdo.parser.v2.XMLParser.parse(XMLParser.java:289)
         ... 17 more
    Thanks.

    We are going to user Employee W-2 PDF.

  • How to deal with empty tags in a SAX Parser

    Hi,
    I hope someone can help me with the problem I am having!
    Basically, I have written an xml-editor application. When an XML file is selected, I parse the file with a SAX parser and save the start and end locations of all the tags and character data. This enables me to display the xml file with the tags all nicely formatted with pretty colours. Truly it is a Joy To Behold. However, I have a problem with tags in this form:
    <package name="boo"/>
    because the SAX parser treats them like this:
    <package name = boo>
    </package>
    for various complex reasons the latter is unaccetable so my question is: Is there some fiendishly clever method to detect tags of this type as they occur, so that I can treat them accordingly?
    Thanks,
    Chris

    I have spent some time on googling for code doing this, but found nothing better, than I had to write in by myself.
    So, it would be something like this. Enjoy :)
    package comd;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.util.Stack;
    import java.util.Enumeration;
    public class EmptyTagsHandler extends DefaultHandler {
         private StringBuilder xmlBuilder;
         private Stack<XmlElement> elementStack;
         private String processedXml;
         private class XmlElement{
              private String name;
              private boolean isEmpty = true;
              public XmlElement(String name) {
                   this.name = name;
              public void setNotEmpty(){
                   isEmpty = false;
         public EmptyTagsHandler(){
              xmlBuilder = new StringBuilder();
              elementStack = new Stack();
         private String getElementXPath(){
              StringBuilder builder = new StringBuilder();
              for (Enumeration en=elementStack.elements();en.hasMoreElements();){
                   builder.append(en.nextElement());
                   builder.append("/");
              return builder.toString();
         public String getXml(){
              return processedXml;
         public void startDocument() throws SAXException {
              xmlBuilder = new StringBuilder();
              elementStack.clear();
              processedXml = null;
         public void endDocument() throws SAXException {
              processedXml = xmlBuilder.toString();
         public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
              if (!elementStack.empty()) {
                   XmlElement elem = elementStack.peek();
                   elem.setNotEmpty();
              xmlBuilder.append("<");
              xmlBuilder.append(qName);
              for (int i=0; i<attributes.getLength();i++){
                   xmlBuilder.append(" ");
                   xmlBuilder.append(attributes.getQName(i));
                   xmlBuilder.append("=");
                   xmlBuilder.append(attributes.getValue(i));
              xmlBuilder.append(">");
              elementStack.push(new XmlElement(qName));
         public void endElement(String uri, String localName, String qName) throws SAXException {
              XmlElement elem = elementStack.peek();
              if (elem.isEmpty) {
                   xmlBuilder.insert(xmlBuilder.length()-1, "/");
              } else {
                   xmlBuilder.append("</");
                   xmlBuilder.append(qName);
                   xmlBuilder.append(">");
              elementStack.pop();
         public void characters(char ch[], int start, int length) throws SAXException {
              if (!elementStack.empty()) {
                   XmlElement elem = elementStack.peek();
                   elem.setNotEmpty();
              String str = new String(ch, start, length);
              xmlBuilder.append(str);
         public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
              String str = new String(ch, start, length);
              xmlBuilder.append(str);
    }

  • ? - Is there a way to validate 1 XML record at a time, using the SAX or oth

    Hello!
    Before running into space problems, i generated an XML file from a 'pipe delimited' file and and then processed that XML file thru a SAXParser 'validator' and the data was correctly validated, using the RELAXNG Schema patterns as the validation criteria!
    But as feared, the XML file was huge! (12 billion XML recs. generated from 1 billion 'pipe' recs.) and i am now trying to find a way to process 1 'pipe' record at a time, (ie) read 1 record from the 'pipe delimited' file, convert that rec. to an XML rec. and then send that 1 XML rec. thru the SAXParser 'validator', avoiding the build of a huge temporary XML file!
    After testing this approach, its looks like the SAXParser 'validator' (sp.parse) is expecting only (1) StringBufferInputStream as input,and after opening, reading and closing just (1) of the returned StringBufferInputStream objects, the validator wants to close up operations!
    Where i have the "<<<<<" you can see where i'm calling the the object.method that creates the 'pipe>XML' records 'sb.createxml' and will be returning many occurances of the StringBufferInputStream object, where (1) StringBufferInputStream object represents (1) 'pipe>XML' record!
    So what i'm wondering, is if there is a form of 'inputStream' class that can be loaded and processed at the same time! ie instead of requiring that the 'inputStream' object be loaded in it's entirety, before going to validation?
    Or if there is another XML 'validator' that can validate 1 XML record at a time, without requiring that the entire XML file be built first?
    1. ---------------------------------class: (SX2) ---------------------------------------------------------------------------------------------------------
    import ............
    public class SX2
    public static void main(String[] args) throws Exception
    MyDefaultHandler dh = new MyDefaultHandler();
    SX1 sx = new SX1();
    SAXParser sp = sx.getParser(args[0]);
    stbuf1 sb = new stbuf1();
    sp.parse(sb.createxml(args[1]),dh); <<<<<< createxml( ) see <<<<<<< below
    class MyDefaultHandler extends DefaultHandler {
    public int errcnt;
    "SX2.java" 87 lines, 2563 characters
    2. ----------------------------------class: (stbuf1) method: (createxml) ----------------------------------------------------------------------------
    public stbuf1 () { }
    public StringBufferInputStream createxml( String inputFile ) <<<<<< createxml(
    BufferedReader textReader = null;
    if ( (inputFile == null) || (inputFile.length() <= 1) )
    {     throw new NullPointerException("Delimiter Input File does not exist");
    String ele = new String();
    try {
    ele = new String();
    textReader = new BufferedReader(new FileReader(inputFile));
    String line = null; String SEPARATOR = "\\|"; String sToken = null;
    String hdr1=("<?xml version=#1.0# encoding=#UTF-8#?>"); hdr1=hdr1.replace('#','"');
    String hdr2=("<hlp_data>");
    String hdr3=("</hlp_data>");
    String hdr4=("<"+TABLE_NAME+">");
    String hdr5=("</"+TABLE_NAME+">");
    while ( (line = textReader.readLine()) != null )
    String[] sa = line.split(SEPARATOR);
    String elel = new String();
    for (int i = 0; i < NUM_COLS; i++)
    if (i>(sa.length-1)) { sToken = new String(); } else { sToken = sa; }
    elel="<"+_columnNames[i]+">"+sToken+"</"+_columnNames[i]+">";
    if (i==0) {
    ele=ele.concat(hdr1);ele=ele.concat(hdr2);ele=ele.concat(hdr4);ele=ele.concat(elel);
    else
    if (i==NUM_COLS - 1) {
    ele=ele.concat(elel);ele=ele.concat(hdr5);ele=ele.concat(hdr3);
    else {
    ele=ele.concat(elel);
    textReader.close();
    catch (IOException e) {
    return (new StringBufferInputStream(ele));
    public static void main( String args[] ) {
    stbuf1 genxml_obj = new stbuf1 ();
    String ptxt=new String(args[0]);
    genxml_obj.createxml(ptxt); }}

    Well,i think you can use the streaming API for xml processing provided by weblogic.It is pull model,not push model like SAX.with it,you can select the events you want without having to react to every event,and you can filter the events out.
    Sun also provide such streaming API for xml processing,and i got an very simple introduction about it on the Chinese Sun developer site.but i couldn't find any other infomation about it elsewhere! If you have such materials,please send to my email:[email protected],and if I have it,i will be sure to post the links here.hope it helps more or less:)
    @smile@

  • How to get the position of a tag in XML,when i am using the org.xml.sax

    Hi,
    I am able to parse a xml document.I want to get the position of a tag in the document.So that by keeping that as reference, i can access other tags.Plz help me.I am using org.xml.sax API.

    Hello Friends
    After research , I could also find another way to check the existence of a node .We can even use CHOOSE to check the existence.
    <xsl:choose>
          <xsl:when test="(/mynode)">
              your action if the mynode is found
          </xsl:when>
          <xsl:otherwise>
                    action if mynode is not found
          </xsl:otherwise>
    </xsl:choose>
    Thanks.
    Wishes
    Richa

  • Get document url in SAX ContentHandler

    Hopefully a simple question, but how to get the name or URL of the current document handled by a SAX ContentHandler? I don't see this in the startDocument or startElement callbacks.

    nm found out about setDocumentLocator

  • How to parse a specific inner element using SAX

    I would like to parse the values of <data> and store them but only the <data> values whose parent element is <process-type>.
    My xml file looks something like:
    <process-type id="IASPT" module-id="IASPT" working-dir="/apps/ora10G5/iaspt/bin">
         <port id="ajp" range="7501-7600"/>
         <process-set id="IASPT" numprocs="1"/>
    </process-type>
    <category id="stop-parameters">
          <data id="java-options" value="-Djava.awt.headless=true"/>
    </category>
    <process-type id="claimservices" module-id="OC4J" status="enabled">
         <environment>
               <variable id="DOCUMENTUM" value="/apps/dctmdev"/>
         </environment>
         <module-data>
               <category id="start-parameters">
                     <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/claimservices/config/java2.policy"/>
               </category>
         </module-data>
    </process-type>
    <process-type id="ASG" module-id="custom">
          <process-set id="ASG" numprocs="1">
             <module-data>
                <category id="start-parameters">
                   <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/sharedservices/config/java2.policy"/>
                </category>
             </module-data>
          </process-set>
    </process-type>
    ......I would like to read the value(s) of data which is within process-type. In this case:
    <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/claimservices/config/java2.policy"/>
    <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/sharedservices/config/java2.policy"/>I can read the elements, attributes and their values using SAX. The problem however is that when I read the file, it reads in not only the line I am interested in but also any <data> element within the XML file which is not what I want. I tried editing my code but it doesn't seem to work.
    The start element in my code looks like this:
    public void startElement(String name, String localName,
                   String qName, Attributes attr) throws SAXException {
              String processTypeId = "";
              String processTypeData = "";
              if (localName.equalsIgnoreCase("process-type")){
                   if (attr.getLocalName(0).equals("id")){
                        processTypeId = attr.getValue(0);
                        System.out.println("process_type/id: " + processTypeId);
              if (localName.equalsIgnoreCase("data")){
                   if (attr.getLocalName(1).equals("value")){
                        processTypeData = attr.getValue(1);
                        System.out.println("data/id: " + processTypeData);
    } Considering I have more than one process-type and that the first attribute of <data>, id, is the same for both, I should somehow tell SAX:
    1) Find process-type element
    2) Read its id attribute
    3) Read <data> element and its attributes under process-type if any
    4) Store <data> and attributes of each process-type (into possibly a map in the form of {process-type id, data value} pair??)
    I would appreciate your help with this very much.

    I thought the same. The good thing is that the first one is the one I want. The bad thing is that the first one might not necessarily be positioned at the top.
    What I mean is when I read this part of the XML file
    <process-type id="home" module-id="OC4J" status="enabled">
         <module-data>
               <category id="start-parameters">
                       <data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy"/>
               </category>
               <category id="stop-parameters">
                       <data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy"/>
               </category>
         </module-data>
    </process-type>I am interested in the value attribute of the <data> under <category> whose id attribute is "start-parameters". The thing is that the "start-parameters" and the "stop-parameters" postions could be switched so I cannot rely on the fact that my code reads the first one successfully.
    I tried editing my code like shown below but no luck
    if (localName.equalsIgnoreCase("process-type")){
                   //Extracting process-type attribute id
                   if (attr.getLocalName(0).equals("id")){
                        processTypeId = attr.getValue(0);
                        System.out.println("\nprocess_type/id: " + processTypeId);
              if (localName.equalsIgnoreCase("category")){
                   //Extracting process-type attribute id
                   if (attr.getLocalName(0).equals("id")){
                        categoryId = attr.getValue(0);
                        if (categoryId.equals("start-parameters")){
                             //System.out.println("\ncategory/id: " + categoryId);     
                             categoryStartParameters = categoryId;
                             startOfCategoryId = true;
              if (localName.equalsIgnoreCase("data")){
                   if (endOfProcessType){
                        if (startOfCategoryId /*&& (categoryStartParameters.equals("start-parameters"))*/){
                             if (attr.getLocalName(1).equals("value")){
                                  processTypeData = attr.getValue(1);
                                  System.out.println("\ndata/id: " + processTypeData);
                                  endOfProcessType = false;
         public void endElement(String uri, String localName, String qName) throws SAXException {
              if( localName.equalsIgnoreCase("process-type") ) {
                  endOfProcessType = true;
    ......Isn't there a more straightforward way to reading all the elements under a particular element in SAX?
    Please assume that all the variables are defined and initialised.

  • XML SAX error in parsing

    Hi,
    I have a large XML file(100KB) and I am using SAX parser for parsing it.
    The part of the code is shown here
    public void characters(char[] ch, int start, int end)
    throws SAXException {
    String s = new String(ch, start, end);
    // System.out.println("characters: " + s);
    if(s == null || s.trim().length() == 0 || s.equals("\n")) {
                   return;
    setValueInObject(s);
    where I assumes that the "s" will be the "value" in my xml for example
    <tag>value<tag>
    This is working fine , in most of the cases. But if the "value" is too large sometimes it gives me part of the value (eg. valu) only. And if i re-try then i may work.
    Please advice me in this regards.
    thanks
    Rajesh

    Just use characters() method for building string. Use endElement() to process that string.

  • XML - SAX Parsing Question

    Hi,
    I am parsing XML using SAX parser and fill the values into the HashTable ( like Key value pair ).. so i can get the vaues for a particular key using hash get function.
    For the following XML. There are 2 "subscriberNumber" attribute, one is under "sn:Subscriber" and the another is under "sn:SubscriberChange".
    I can able to put this values in hash table and when i print the Hash table it is printing as sn:subscriberNumber=[1234567890, 1234567890] .. But how will i know which one is from "sn:Subscriber" and which is from "sn:SubscriberChange"
    This is the XML :
    <sn:SubscriberNotification>
    <sn:notificationSubType>1120</sn:notificationSubType>
    <sn:Subscriber>
         <cng:PaymentType>PostPaid</cng:PaymentType>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:Subscriber>
    <sn:SubscriberChange>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:SubscriberChange>
    </sn:SubscriberNotification>
    Any suggestion and pointers are really helpful
    Thanks,
    -Raj..

    Try something like this:
    import java.util.Stack;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    class MyHandler extends DefaultHandler {
        Stack openTags = new Stack();
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equals("sn:subscriberNumber")) {
                String parentTag = (String)openTags.peek();
                System.out.println("Parent tag of this <sn:subscriberNumber> is : <" + parentTag + ">");
            openTags.push(qName);
        public void endElement(String uri, String localName, String qName) throws SAXException {
            openTags.pop();
    }Regards

Maybe you are looking for

  • Time detection is broken in Mac OS 10.9.1.

    Time detection is broken in Mac OS 10.9.1. I'm living in Minsk (GMT +3). Time zone detects correctly, updating time from servers is turned on. But time is always leads +3 hours. How to fix it? Maybe time settings conflics with Windows 7?

  • Indesign CS6 and Windows 8

    Indesign CS6 is extreamly slow in Windows 8 espeially in editing Text.

  • Connect iphone to internet through macbook

    How do I connect my iphone to the internet through my macbook which is connecting to the internet through broadband

  • Is there any recursive function in DB2

    Hi all, Could you please tell me is there any recursive function in DB2 and if yes then please provide me a sample code. I want to write a function as below but it's giving me following error: >[Error] Script lines: 1-33 - ( DB2 SQL error: SQLCODE: -

  • Failed to create deployable object 'local/Calendar' since it not a WD objec

    Hi I created a calendar application in Web dynpro,There iam getting this error .will any one please help me how to avoid this. com.sap.tc.webdynpro.services.sal.core.DispatcherException: The requested deployable object 'local/Calendar' and applicatio