HO w to use SAX parser to create an XML file on the fly

Hi All,
Currently I am using the DOM parser to create an XML file from a text file. But as the DOM takes much memory and inefficient, I need to convert the DOM translator to SAX translator. Can I do that ?? If YES then how to go about that and if NO then what may be the workaround for that.
Please help me out
Thanx in advance
kaushik

Incidentally, look at this thread:
http://forum.java.sun.com/thread.jsp?forum=34&thread=252415
It has an example of how to transform an XML file via XSLT. If you change this to use the zero-argument form of newTransformer, it will apply the "identity transformation" to your input, thus outputting your XML in valid form. Now you just need to figure out how to provide SAX input to this, and the JAXP download includes an example of that.

Similar Messages

  • Can we create a XDP file on the fly

    Hi All,
    I am new to Live Cycle.
    I want to know if we can create an XDP file on the fly and immediately using this XDP file can form server create a PDF?
    Need this info urgently..
    Thanks in advance.
    Regards
    Vinay

    There are several ways to do this. The third chapter in the
    cookbook is a good place to start.
    All things in ActionScript are based on objects. Constructing
    them with the data needed for the ui information you will need and
    then binding that data to your dashboard objects is basically what
    you are going to be doing.
    For me it makes the most sence to have an idea of what
    different types of objects you will be creating and create some
    extended components for those objects. Then when you recieve your
    data, binary or xml, you can digest the configuration settings from
    the layout and populate the constructor for each of your
    components.
    It sounds like you need to organize your layout structure in
    a heirarchy and from that you can walk each branch and create each
    set of things as you parse your data.
    Without a bit more information as to what you are
    specifically doing that is about as far as I can go minus adding in
    some code along some line that I think might work.
    Hope that helps some.
    -D

  • SAX: How to create new XML file using SAX parser

    Hi,
    Please anybody help me to create a XML file using the Packages in the 5.0 pack of java. I have successfully created it reading the tag names and values from database using DOM but can i do this using SAX.
    I am successful to read XML using SAX, now i want to create new XML file for some tags and its values using SAX.
    How can i do this ?
    Sachin Kulkarni

    SAX is a parser, not a generator.Well,
    you can use it to create an XML file too. And it will take care of proper encoding, thus being much superior to a normal textwriter:
    See the following code snippet (out is a OutputStream):
    PrintWriter pw = new PrintWriter(out);
          StreamResult streamResult = new StreamResult(pw);
          SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
          //      SAX2.0 ContentHandler.
          TransformerHandler hd = tf.newTransformerHandler();
          Transformer serializer = hd.getTransformer();
          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"pdfBookmarks.xsd");
          serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://schema.inplus.de/pdf/1.0");
          serializer.setOutputProperty(OutputKeys.METHOD,"xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");
          hd.setResult(streamResult);
          hd.startDocument();
          //Get a processing instruction
          hd.processingInstruction("xml-stylesheet","type=\"text/xsl\" href=\"mystyle.xsl\"");
          AttributesImpl atts = new AttributesImpl();
          atts.addAttribute("", "", "someattribute", "CDATA", "test");
          atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
           hd.startElement("", "", "MyTag", atts);
    String curTitle = "Something inside a tag";
              hd.characters(curTitle.toCharArray(), 0, curTitle.length());
        hd.endElement("", "", "MyTag");
          hd.endDocument();
    You are responsible for proper nesting. SAX takes care of encoding.
    Hth
    ;-) stw

  • How do I create individual xml files from the parsed data output of a xml file?

    I have written a program (DOM Parser) that parses data from a XMl File. I would like to create an individual file with the corresponding name for each set of data parsed from the xml document. If the parsed output is Single, Double, Triple, I would like to create an individual xml file (Single.xml, Double.xml, Triple.xml)with those corresponding names. How do I create the xml files and give each file the name of my parsed data output? Thanks in advance for your help.
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println("Template" + ": " +templateElement.getAttribute("name")+ ".xml");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

    Ive posted the new code but now I'm getting a FileAlreadyExistException error. How do I handle this exception error correctly in my code?
    import java.io.IOException;
    import java.nio.file.FileAlreadyExistsException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println(templateElement.getAttribute("name")+ ".xml");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      String fileName = templateElement.getAttribute("name") + ".xml";
      Files.createFile(Paths.get(fileName));
      System.out.println("File" + ":" + fileName + ".xml created");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

  • How to create a xml file from the jsp page?

    I'm a beginner of the develop xml,my question like this,
    there has a jsp page,some parameters in it,I wanna get the parameters and create a xml file,so,what parser method should I use?
    And how to create a new xml file,when the file haven't exist at first?
    pls give some code,thanks.

    a ggod link for u http://www.theserverside.com/resources/article.jsp?l=JSP-XML2

  • Approach to parse large number of XML files into the relational table.

    We are exploring the option of XML DB for processing a large number of files coming same day.
    The objective is to parse the XML file and store in multiple relational tables. Once in relational table we do not care about the XML file.
    The file can not be stored on the file server and need to be stored in a table before parsing due to security issues. A third party system will send the file and will store it in the XML DB.
    File size can be between 1MB to 50MB and high performance is very much expected other wise the solution will be tossed.
    Although we do not have XSD, the XML file is well structured. We are on 11g Release 2.
    Based on the reading this is what my approach.
    1. CREATE TABLE XML_DATA
    (xml_col XMLTYPE)
    XMLTYPE xml_col STORE AS SECUREFILE BINARY XML;
    2. Third party will store the data in XML_DATA table.
    3. Create XMLINDEX on the unique XML element
    4. Create views on XMLTYPE
    CREATE OR REPLACE FORCE VIEW V_XML_DATA(
       Stype,
       Mtype,
       MNAME,
       OIDT
    AS
       SELECT x."Stype",
              x."Mtype",
              x."Mname",
              x."OIDT"
       FROM   data_table t,
              XMLTABLE (
                 '/SectionMain'
                 PASSING t.data
                 COLUMNS Stype VARCHAR2 (30) PATH 'Stype',
                         Mtype VARCHAR2 (3) PATH 'Mtype',
                         MNAME VARCHAR2 (30) PATH 'MNAME',
                         OIDT VARCHAR2 (30) PATH 'OID') x;
    5. Bulk load the parse data in the staging table based on the index column.
    Please comment on the above approach any suggestion that can improve the performance.
    Thanks
    AnuragT

    Thanks for your response. It givies more confidence.
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    TNS for Linux: Version 11.2.0.3.0 - Production
    Example XML
    <SectionMain>
    <SectionState>Closed</SectionState>
    <FunctionalState>CP FINISHED</FunctionalState>
    <CreatedTime>2012-08</CreatedTime>
    <Number>106</Number>
    <SectionType>Reel</SectionType>
    <MachineType>CP</MachineType>
    <MachineName>CP_225</MachineName>
    <OID>99dd48cf-fd1b-46cf-9983-0026c04963d2</OID>
    </SectionMain>
    <SectionEvent>
    <SectionOID>99dd48cf-2</SectionOID>
    <EventName>CP.CP_225.Shredder</EventName>
    <OID>b3dd48cf-532d-4126-92d2</OID>
    </SectionEvent>
    <SectionAddData>
    <SectionOID>99dd48cf2</SectionOID>
    <AttributeName>ReelVersion</AttributeName>
    <AttributeValue>4</AttributeValue>
    <OID>b3dd48cf</OID>
    </SectionAddData>
    - <SectionAddData>
    <SectionOID>99dd48cf-fd1b-46cf-9983</SectionOID>
    <AttributeName>ReelNr</AttributeName>
    <AttributeValue>38</AttributeValue>
    <OID>b3dd48cf</OID>
    <BNCounter>
    <SectionID>99dd48cf-fd1b-46cf-9983-0026c04963d2</SectionID>
    <Run>CPFirstRun</Run>
    <SortingClass>84</SortingClass>
    <OutputStacker>D2</OutputStacker>
    <BNCounter>54605</BNCounter>
    </BNCounter>
    I was not aware of Virtual column but looks like we can use it and avoid creating views by just inserting directly into
    the staging table using virtual column.
    Suppose OID id is the unique identifier of each XML FILE and I created virtual column
    CREATE TABLE po_Virtual OF XMLTYPE
    XMLTYPE STORE AS BINARY XML
    VIRTUAL COLUMNS
    (OID_1 AS (XMLCAST(XMLQUERY('/SectionMain/OID'
    PASSING OBJECT_VALUE RETURNING CONTENT)
    AS VARCHAR2(30))));
    1. My question is how then I will write this query by NOT USING COLMUN XML_COL
    SELECT x."SECTIONTYPE",
    x."MACHINETYPE",
    x."MACHINENAME",
    x."OIDT"
    FROM po_Virtual t,
    XMLTABLE (
    '/SectionMain'
    PASSING t.xml_col                          <--WHAT WILL PASSING HERE SINCE NO XML_COL
    COLUMNS SectionType VARCHAR2 (30) PATH 'SectionType',
    MachineType VARCHAR2 (3) PATH 'MachineType',
    MachineName VARCHAR2 (30) PATH 'MachineName',
    OIDT VARCHAR2 (30) PATH 'OID') x;
    2. Insetead of creating the view then Can I do
    insert into STAGING_table_yyy ( col1 ,col2,col3,col4,
    SELECT x."SECTIONTYPE",
    x."MACHINETYPE",
    x."MACHINENAME",
    x."OIDT"
    FROM xml_data t,
    XMLTABLE (
    '/SectionMain'
    PASSING t.xml_col                         <--WHAT WILL PASSING HERE SINCE NO XML_COL
    COLUMNS SectionType VARCHAR2 (30) PATH 'SectionType',
    MachineType VARCHAR2 (3) PATH 'MachineType',
    MachineName VARCHAR2 (30) PATH 'MachineName',
    OIDT VARCHAR2 (30) PATH 'OID') x
    where oid_1 = '99dd48cf-fd1b-46cf-9983';<--VIRTUAL COLUMN
    insert into STAGING_table_yyy ( col1 ,col2,col3
    SELECT x."SectionOID",
    x."EventName",
    x."OIDT"
    FROM xml_data t,
    XMLTABLE (
    '/SectionMain'
    PASSING t.xml_col                         <--WHAT WILL PASSING HERE SINCE NO XML_COL
    COLUMNS SectionOID PATH 'SectionOID',
    EventName VARCHAR2 (30) PATH 'EventName',
    OID VARCHAR2 (30) PATH 'OID',
    ) x
    where oid_1 = '99dd48cf-fd1b-46cf-9983';<--VIRTUAL COLUMN
    Same insert for other tables usind the OID_1 virtual coulmn
    3. Finaly Once done how can I delete the XML document from XML.
    If I am using virtual column then I beleive it will be easy
    DELETE table po_Virtual where oid_1 = '99dd48cf-fd1b-46cf-9983';
    But in case we can not use the Virtual column how we can delete the data
    Thanks in advance
    AnuragT

  • Creating an xml file from the Basic java Object

    how to create an XML file using the values available in the object with reference to an xsd or dtd file..
    (OR )
    is it possible to write the contents of an object to an xml file without knowing the dtd or xsd file .......

    how to create an XML file using the values available in the object with reference to an xsd or dtd file..
    (OR )
    is it possible to write the contents of an object to an xml file without knowing the dtd or xsd file .......

  • How to create an XML file from scratch ?

    Hi all,
    I'm afraid that I will seem dummy, but I think I really misunderstand something or I'm trying to do something that is not possible...
    I would like to create a XML file containing the following:<?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet type="text/xsl" href="pl.xsl"?>
    <!DOCTYPE playlist SYSTEM "pl.dtd">
    <playlist id="2">
    </playlist>I really need to have both the stylesheet and the DOCTYPE declarations... Does anyone know if this is possible ?
    To create the XML Document, I am using the DocumentBuilder object from javax.xml package (jaxp-1.2-ea2). I think this, at least, is correct.
    To print out the XML document I have tried to use :
    - the Transformer from javax.xml package (jaxp-1.2-ea2) but I could obtain only the DOCTYPE declaration.
    - the Serializer from Xerces parser (version 2.0.1) to print out the Document I am creating with the jaxp, but I was able only to obtain the stylesheet declaration...
    So far I have just understand that there is a difference between Serializer and Transformer (one is serializing, and the other is transforming ;-)), but I couldn't figure out which one would be suitable to produce the XML file above...
    I would really appreciate if one could help me with that ;-)
    Thanks,
    Karau

    Could send me an example ?
    For the moment I am using Transformer in that way:
         TransformerFactory tfactory = TransformerFactory.newInstance();
         try {
             Transformer transformer = tfactory.newTransformer();
             DOMSource source = new DOMSource(playlistDoc.getDocumentElement());
             StreamResult res = new StreamResult(new File(path));
             transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PL_DTD);
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             transformer.transform(source, res);
         catch (TransformerConfigurationException tce) {
             throw tce;
         catch (TransformerException te) {
             throw te;
         }

  • How to create an XML File for Gantt?

    Hi Everybody.
    I need a Gantt in Web Dynpro ABAP. I need it for the boss to do a Forecast for Vacation. I Hope this is understanding.
    Did Anyone know how can i create a XML File for the Gantt at runtime?
    Thanks
    MSi

    Hi Marcus,
    the following link is to the JNet/JGantt developer doco
    [JNet/JGantt Developer Documentation|http://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/lw/uuid/f010ec31-9658-2910-3c83-c6e62904eceb]
    included in this is the:
    [Schema for XML|http://www.sdn.sap.com/irj/sdn/go/portal/prtroot/com.sap.km.cm.docs/lw/webdynpro/jnet_jgantt%20developer%20documentation/schema/xml-spy/jnet-schema.html]
    You can use this to build XML to represent a gantt like chart.
    I did this to build XML to represent employee avaliablity - although we fronted the gantt through WD Java not ABAP - the java applet called is the same (I believe).
    Don't underestimate the work required to tweek your data into a decent layout. It took me days.
    There may be tools/api to help generate the XML - I don't know of them - I'd look forward to seeing any other replies to this thread from people who have used/built any.  An example of a class that generates JNet XML - CL_SPI_UI_JNET - but this does not seem to be a Gantt display.
    Cheers,
    Chris

  • How to create new XML file using retreived XML content by using SAX API?

    hi all,
    * How to create new XML file using retreived XML content by using SAX ?
    * I have tried my level best, but output is coming invalid format, my code is follows,
    XMLFileParser.java class :-
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.XMLFilterImpl;
    public class PdfParser extends XMLFilterImpl {
        private TransformerHandler handler;
        Document meta_data;
        private StringWriter meta_data_text = new StringWriter();
        public void startDocument() throws SAXException {
        void startValidation() throws SAXException {
            StreamResult streamResult = new StreamResult(meta_data_text);
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try
                handler = factory.newTransformerHandler();
                Transformer transformer = handler.getTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                handler.setResult(streamResult);
                handler.startDocument();
            catch (TransformerConfigurationException tce)
                System.out.println("Error during the parse :"+ tce.getMessageAndLocation());
            super.startDocument();
        public void startElement(String namespaceURI, String localName,
                String qualifiedName, Attributes atts) throws SAXException {
            handler.startElement(namespaceURI, localName, qualifiedName, atts);
            super.startElement(namespaceURI, localName, qualifiedName, atts);
        public void characters(char[] text, int start, int length)
                throws SAXException {
            handler.characters(text, start, length);
            super.characters(text, start, length);
        public void endElement(String namespaceURI, String localName,
                String qualifiedName) throws SAXException {
            super.endElement("", localName, qualifiedName);
            handler.endElement("", localName, qualifiedName);
        public void endDocument() throws SAXException {
        void endValidation() throws SAXException {
            handler.endDocument();
            try {
                TransformerFactory transfactory = TransformerFactory.newInstance();
                Transformer trans = transfactory.newTransformer();
                SAXSource sax_source = new SAXSource(new InputSource(new StringReader(meta_data_text.toString())));
                DOMResult dom_result = new DOMResult();
                trans.transform(sax_source, dom_result);
                meta_data = (Document) dom_result.getNode();
                System.out.println(meta_data_text);
            catch (TransformerConfigurationException tce) {
                System.out.println("Error occurs during the parse :"+ tce.getMessageAndLocation());
            catch (TransformerException te) {
                System.out.println("Error in result transformation :"+ te.getMessageAndLocation());
    } CreateXMLFile.java class :-
    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();
    Sax.endElement("", "basic-metadata", "basic-metadata");* In CreateXMLFile.java
    class, I have retreived the xml content in the meta_data object, after that i have converted into character array and this will be sends to SAX
    * In this case , the XML file created successfully but the retreived XML content added as an text in between basic-metadata Element, that is, retreived XML content
    is not an XML type text, it just an Normal text Why that ?
    * Please help me what is the problem in my code?
    Cheers,
    JavaImran

    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    </code><code>Sax.endElement("", "basic-metadata", "basic-metadata");</code>
    <code class="jive-code jive-java">Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();     
    * I HAVE CHANGED MY AS PER YOUR SUGGESTION, NOW SAME RESULT HAS COMING.
    * I AM NOT ABLE TO GET THE EXACT OUTPUT.,WHY THAT ?
    Thanks,
    JavaImran{code}

  • Problem in parsing an XML using SAX parser

    Hai All,
    I have got a problem in parsing an XML using SAX parser.
    I have an XML (sample below) which need to be parsed
    <line-items>
    <item num="1">
         <part-number>PN1234</part-number>
         <quantity uom="ea">10</quantity>
         <lpn>LPN1060</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="2">
         <part-number>PN1527</part-number>
         <quantity uom="lbs">5</quantity>
         <lpn>LPN2152</lpn>
         <reference num="1">Line ref 1</reference>
         <reference num="2">Line ref 2</reference>
         <reference num="3">Line ref 3</reference>
    </item>
    <item num="n">
    </item>
    </line-items>
    There can be any number of items( 1 to n). I need to parse these
    item values using SAX parser and invoke a stored procedure for
    each item with its
    values(partnumber,qty,lpn,refnum1,refnum2,refnum3).
    Suppose if there are 100 items, i need to invoke the stored
    procedure sp1() 100 times for each item.
    I need to invoke the stored procedure in endDocument() method of
    SAX event handler and not in endelement() method.
    What is the best way to store those values and invoke the stored
    procedure in enddocument() method.
    Any help would br greatly appreciated.
    Thanks in advance
    Pooja.

    VO or ValueObject is a trendy new name for Beans.
    So just create an item class with variables for each of the sub elements.
    <item>
    <part-number>PN1234</part-number>
    <quantity uom="ea">10</quantity>
    <lpn>LPN1060</lpn>
    <reference num="1">Line ref 1</reference>
    <reference num="2">Line ref 2</reference>
    <reference num="3">Line ref 3</reference>
    </item>
    public class ItemVO
    String partNumber;
    int quantity;
    String quantityType;
    String lpn;
    List references = new ArrayList();
    * @return Returns the lpn.
    public String getLpn()
    return this.lpn;
    * @param lpn The lpn to set.
    public void setLpn(String lpn)
    this.lpn = lpn;
    * @return Returns the partNumber.
    public String getPartNumber()
    return this.partNumber;
    * @param partNumber The partNumber to set.
    public void setPartNumber(String partNumber)
    this.partNumber = partNumber;
    * @return Returns the quantity.
    public int getQuantity()
    return this.quantity;
    * @param quantity The quantity to set.
    public void setQuantity(int quantity)
    this.quantity = quantity;
    * @return Returns the quantityType.
    public String getQuantityType()
    return this.quantityType;
    * @param quantityType The quantityType to set.
    public void setQuantityType(String quantityType)
    this.quantityType = quantityType;
    * @return Returns the references.
    public List getReferences()
    return this.references;
    * @param references The references to set.
    public void setReferences(List references)
    this.references = references;

  • Problem in using SAX parser.

    Hai All,
    I have got a problem in using SAX parser.
    My XML looks like this:
    <authorizer>
    <first-name>HP</first-name>
    <last-name>Services</last-name>
    <phone>800-22-1984</phone>
    </authorizer>
    <destination>
    <first-name>John</first-name>
    <last-name>Doe</last-name>
    <company>John Doe Enterprises, Inc.</company>
    <department>Manufacturing</department>
    <phone>800-555-1234</phone>
    <address>
    <street-one>1654 Peachtree Str</street-one>
    <street-two>Suite Y</street-two>
    <city>Atlanta</city>
    <province>GA</province>
    <country>US</country>
    <postal-code>30326</postal-code>
    </address>
    </destination>
    my part of SAX parser code is:
    public void startElement (String name, AttributeList attrs)
    throws SAXException
    accumulator.setLength(0);
    public void characters (char buf [], int offset, int len)
    throws SAXException
    accumulator.append(buf, offset, len);
    public void endElement (String name)
    throws SAXException
    if (name.equals("first-name") )
    firstname=accumulator.toString().trim();
    if (name.equals("last-name"))
    lastname=accumulator.toString().trim();
    My problem is that i have to store the values of first-name and last-name.
    but i have that in both
    <authorizer> </authorizer> Tag and
    <destination> </destination>
    I need to retrive authorizer's firstname,lastname and
    destination's firstname and lastname.
    what i mean is i need to store authorizerFirstName,authorizerLastName
    destinationFirstname and destinationLastname.
    Pls let me know how to do that.
    Thanks in advance.
    Pooja.

    hi pooja,
    I think you are using DataHandler for parsing. Its deprecated. try using contentHandler . You can get the value of the element at the beginning. say for example
    <firstname>sdfs</firstname>
    the startElement will be firstname
    the next method that it invokes will be characters method which has the text associated with the element. I am sending a sample code for your problem. try using it .
    boolean m_boolinAuth = false;
    boolean m_boolinDest = false;
    boolean m_bAuthFName = false;
    boolean m_bAuthLName = false;
    public void startElement(String namespaceURI, String elementName, String qName, Attributes atts)
    //does the logic for startElement
    if(qName.equals("Authorization"))
    m_boolinAuth = true;
    m_boolinDest = false;
    else if(qName.equals("Destination"))
    m_boolinDest = true;
    m_boolinAuth = false;
    if(qName.equals("firstname"))
    m_bFirstName = true;
    if(qName.equals("lastname"))
    m_bLastName = true;
    public void characters(char[] ch, int start, int length)
    //does the logic for characters.
    String str = new String(ch,start,length);
    if(m_bFirstName)
    if(m_boolinAuth)
    m_strAuthFirstName =str;
    else if(m_boolinDest)
    m_strDestFirstName = str;
    m_bFirstName = false;
    if(m_bLastName)
    //same as first name case;
    }

  • XML to CSV using SAX Parser

    Hello
    I need to convert xml files to csv format using SAX Parser. The following code & outputs are as below:
    XML file:
    <Library>
    <Book>
         <Title>Professional JINI</Title>
         <Author>bs</Author>
         <Publisher>Oreilly Publications</Publisher>
    </Book>
    <Book>
         <Title>XML Programming</Title>
         <Author>java</Author>
         <Publisher>Mann Publications</Publisher>
    </Book>
    </Library>
    public class BooksLibrary extends DefaultHandler
    protected static final String XML_FILE_NAME = "C:\\library1.xml";
         public static void main (String argv [])
              // Use the default (non-validating) parser
              SAXParserFactory factory = SAXParserFactory.newInstance();
              try {
                   FileOutputStream fos=new FileOutputStream("C:/test.txt");
                   // Set up output stream
                   out = new OutputStreamWriter (fos, "UTF8");
                   // Parse the input
                   SAXParser saxParser = factory.newSAXParser();
                   saxParser.parse( new File(XML_FILE_NAME), new BooksLibrary() );
              } catch (Throwable t) {
                   t.printStackTrace ();
              System.exit (0);
         static private Writer out;
         //===========================================================
         // Methods in SAX DocumentHandler
         //===========================================================
         public void startDocument ()
         throws SAXException
              showData ("<?xml version='1.0' encoding='UTF-8'?>");
              newLine();
         public void endDocument ()
         throws SAXException
              try {
                   newLine();
                   out.flush ();
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
         public void startElement (String name, Attributes attrs)
         throws SAXException
              showData ("<"+name);
              if (attrs != null) {
                   for (int i = 0; i < attrs.getLength (); i++) {
                        showData (" ");
                        showData (attrs.getLocalName(i)+"=\""+attrs.getValue (i)+"\"");
              showData (">");
         public void endElement (String name)
         throws SAXException
              showData ("</"+name+">");
         public void characters (char buf [], int offset, int len)
         throws SAXException
              String s = new String(buf, offset, len);
              showData (s);
         //===========================================================
         // Helpers Methods
         //===========================================================
         // Wrap I/O exceptions in SAX exceptions, to
         // suit handler signature requirements
         private void showData (String s)
         throws SAXException
              try {
                   out.write (s);
                   out.flush ();
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
         // Start a new line
         private void newLine ()
         throws SAXException
              //String lineEnd = System.getProperty("line.separator");
              try {
                   out.write (", ");
              } catch (IOException e) {
                   throw new SAXException ("I/O error", e);
    --------------------------------------------------------------------------------------------------output is as follows:
    <?xml version='1.0' encoding='UTF-8'?>,
         Professional JINI
         bs
         Oreilly Publications
         XML Programming
         java
         Mann Publications
    Can anyone please tell me how to remove that indentation space & get the output as :
    <?xml version='1.0' encoding='UTF-8'?>, Professional JINI, bs, Oreilly Publications, XML Programming, java, Mann Publications
    Thanks

    By the way, there is a new feature in Java 5.0 (Tiger) called "Annotations."
    Since your code extneds DefaultHandler, you could specify a line with
    @Override
    before the definition of each of your methods. If you had used these, the compiler would have given an error since your methods did not override the methods of DefaultHandler.
    (If your code implemented ContentHandler, by contrast, using @Override is invalid because you need to implement all of the methods defined in the interface definition.)
    The other comment is that the safest way to handle characters() data is to use a StringBuilder/Buffer (StringBuilder is only valid in 5.0, StringBuffer has been around since Release 1.0) that you define in the startElement method. Use the append method to gather data presented to you in the characters() method and use toString() to harvest the data in the endElement method.
    Dave Patterson

  • How to use SAX parser in J2ME

    Please help me how to use SAX parser in J2ME.
    Is there any function to find the value of a particular element from a XML file?
    I am able to get Element name, Values, Attributes. But control is not in my hand, DefaultHanldler automatically invokes Character method, then only I am able to get values. But I don't know when this method gets invoked.
    Is there any way or method so that I can get value of any element or attribute just by passing element name as parameter in SAX parser?
    Is there any other parser through which I can perform this task in J2ME?
    Thanks in advance.

    Hi..
    have a look at this.
    http://www-128.ibm.com/developerworks/library/wi-parsexml/
    MeTitus

  • Code to read xml file  and display that data using sax parser

    Hai
    My problem I have to read a xml file and display the contents of the file on console using sax parser.

    here you go

Maybe you are looking for

  • Se518 no account assignment exists for service line

    Hi Experts, We are using SRM701 Patch 04. I am creating a RFx with a limit item then create the purchase order based on the accepted bid. We found the error message SE518 in backend system via /SAPPO/PPO2 when we are using the driver function "/SAPSR

  • Using OSX 10.5 with DynDNS...how do I get the silly host info from ISP out

    Hi There, As I said, running an OSX server from home. Connects using DHCP so it pulls all the host info from the ISP. I'm using DynDNS for a domain I have registered. I can access the server from internet using my domain but how do I get all the host

  • Check a range of values in the pai section of a dynpro

    Hi, I have a week timetable, and for each day the user has to introduce a range of hours. I need to control that the hours the user introduces is in a correct format (hh:mm). I've seen that it's possible to set the valid range of values of an element

  • Automatic clearing with special G/L transaction

    Hi, Does anyone know to clear in mass customers that have line items with special G/L indicators? Regards, Ronan

  • E90 - Maximum Length of Contacts

    Dear All, I am in the process of buying a E90 communicator (Middle East). My current phone is an imate (2004) (Win CE OS). I have a huge contacts database (64 MB) which i would need to migrate to the new communicator. Can any one of you advise if it