How to Create XML file with SAX parser instead of DOM parser

HI ALL,
I am in need of creating an XML file by SAX parser ONLY. As far as my knowledge goes, we can use DOM for such purpose(by using createElement, creatAttribute ...). Can anyone tell me, is there any way to create an XML file using SAX Parser only. I mean, I just want to know whether SAX provides any sort of api for Creatign an element, attribute etc. I know that SAX is for event based parsing. But my requirement is to create an XML file from using only SAX parser.
Any help would be appreciated
Thanx in advance
Kaushik

Hi,
You must write a XMLWriter class yourself, and that Class extends DefaultHandle ....., the overwrite the startElement(url, localName, qName, attributeList), startDocument(), endElement().....and so on.
in startElement write your own logic about how to create a new element and how to create a Attribute list
in startDocument write your own logic about how to build a document and encodeType, dtd....
By using:
XMLWriter out = new XMLWriter()
out.startDocument();
Attribute attr1 = new Atribute();
attr1.add("name", "value");
out.startElement("","","Element1", attr1);
Attribute attr2 = new Atribute();
attr2.add("name", "value");
out.startElement("","","Element2", attr2);
out.endElement("","","Element2");
out.endElement("","","Element1");
out.endDocument();

Similar Messages

  • How to create xml file from Oracle and sending the same xml file to an url

    How to create xml file from Oracle and sending the same xml file to an url

    SQL/XML (XMLElement, XMLForest, XMLAgg, etc) and UTL_HTTP.
    Whether that works for you with the version of Oracle you have, your requirements, and needs is another story. A little detail goes a long way.

  • Creating XML files with the DME

    Hi All,
    I'm working on an integration project between my company and HSBC, they are requesting that we supply our AP payment files for foreign currency in XML format.
    I have some limited experience with the DME and know it can create XML files, however, the elements available for XML files are different to standard flat files. Also it doesnt seem like I can create files with multiple levels? e.g.
    <InitgPty>
    ......... <Id>
    ............... <OrgId>
    ...................... <BkPtyId>ABC00103003</BkPtyId>
    .............. </OrgId>
    ........ </Id>
    </InitgPty>
    Does anyone have any documentation or experience with creating XML files with DME?
    thanks
    Phil.

    Hi,
    Please ask any Implementation team in ABAB or Report painter team with your friends,
    Thanks and REgards
    N.Soma Sundaram

  • How to validate xml file with XSD schema ??  in JDK1.4.2

    How to validate xml file with XSD schema ?? in JDK1.4.2
    i dont want to use new Xerec Jar ...
    Suggest option ...

    Please do not double-post. http://forum.java.sun.com/thread.jspa?threadID=5134447&tstart=0
    Then use Stax (Woodstock) or Saxon.
    - Saish

  • How to create pdf files with text field data

    how to create pdf files with text field data

    That looks like it should work, but it doesn't.
    I opened the PDF I had created from Word in Acrobat (X Pro). Went to File > Properties. Selected "Change Settings". I then enabled "Restrict editing...", set a password, set "Printing Allowed" to "none", "Changes Allowed" to "none", and ensured that "Enable copying of text..." was disabled.
    I saved the PDF file, closed Acrobat, opened the PDF in Reader, and I was still able to select text and graphical objects.
    I reopened the PDF in Acrobat, and the document summart still shows everything as allowed. When I click on "show details" (from File > Properties) it shows the correct settings.
    Any ideas?

  • Reading xml file with sax parser: unknown protocol: c

    Hi,
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"
    Also, I did some testing and I can read a small xml file with just a few elements, but on large complex files, I get that error.
    anyone ever run into this before?
    bp
    Edited by: badperson on Nov 1, 2008 2:19 PM

    badperson wrote:
    I've been googling around, and the best I can find is that the file name:
    File test = new File("lib/test/parseTest/validate-test.xml");should be a url:
    File test = new File("File://lib/test/parseTest/validate-test.xml");
    No, that's wrong. The parameter for that constructor is a file path (relative or absolute). Not a URL. You must have misunderstood whatever you read.
    but I'm working on a linux machine and can't put "File://c:/pathToFile/file.xml"What kind of a Linux machine is this which has a C drive? You must have misunderstood whoever told you to do that.

  • Create xml file with values from context

    Hi experts!
    I am trying to implement a WD application that will have some input fields, the value of those input fields will be used to create an xml file with a certain format and then sent to a certain application.
    Apart from this i want to read an xml file back from the application and then fill some other context nodes with values from the xml file.
    Is there any standard used code to do this??
    If not how can i do this???
    Thanx in advance!!!
    P.S. Points will be rewarded to all usefull answers.
    Edited by: Armin Reichert on Jun 30, 2008 6:12 PM
    Please stop this P.S. nonsense!

    Hi,
    you need to create three util class for that:-
    XMLHandler
    XMLParser
    XMLBuilder
    for example in my XML two tag item will be there e.g. Title and Organizer,and from ur WebDynpro view you need to pass value for the XML tag.
    And u need to call buildXML()function of builder class to generate XML, in that i have passed bean object to get the values of tags. you need to set the value in bean from the view ui context.
    Code for XMLBuilder:-
    Created on Apr 4, 2006
    Author-Anish
    This class is to created for having function for to build XML
    and to get EncodedXML
      and to get formated date
    package com.idb.events.util;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import com.idb.events.Event;
    public class XMLBuilder {
    This attribute represents the XML version
         private static final double VERSION_NUMBER = 1.0;
    This attribute represents the encoding
         private static final String ENCODING_TYPE = "UTF-16";
         /*Begin of Function to buildXML
    return: String
    input: Event
         public String buildXML(Event event) {
              StringBuffer xmlBuilder = new StringBuffer("<?xml version=\"");
              xmlBuilder.append(VERSION_NUMBER);
              xmlBuilder.append("\" encoding=\"");
              xmlBuilder.append(ENCODING_TYPE);
              xmlBuilder.append("\" ?>");
              xmlBuilder.append("<event>");
              xmlBuilder.append(getEncodedXML(event.getTitle(), "title"));
              xmlBuilder.append(getEncodedXML(event.getOrganizer(), "organizer"));
              xmlBuilder.append("</event>");
              return xmlBuilder.toString();
         /End of Function to buildXML/
         /*Begin of Function to get EncodedXML
    return: String
    input: String,String
         public String getEncodedXML(String xmlString, String tag) {
              StringBuffer begin = new StringBuffer("");
              if ((tag != null) || (!tag.equalsIgnoreCase("null"))) {
                   begin.append("<").append(tag).append(">");
                   begin.append("<![CDATA[");
                   begin.append(xmlString).append("]]>").append("</").append(
                        tag).append(
                        ">");
              return begin.toString();
         /End of Function to get EncodedXML/
         /*Begin of Function to get formated date
    return: String
    input: Date
         private final String formatDate(Date inputDateStr) {
              String date;
              try {
                   SimpleDateFormat simpleDateFormat =
                        new SimpleDateFormat("yyyy-MM-dd");
                   date = simpleDateFormat.format(inputDateStr);
              } catch (Exception e) {
                   return "";
              return date;
         /End of Function to get formated date/
    Code for XMLParser:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLParser {
    Enables namespace functionality in parser
         private final boolean isNameSpaceAware = true;
    Enables validation in parser
         private final boolean isValidating = true;
    The SAX parser used to parse the xml
         private SAXParser parser;
    The XML reader used by the SAX parser
         private XMLReader reader;
    This method creates the parser to parse the user details xml.
         private void createParser()
              throws SAXException, ParserConfigurationException {
              // Create a JAXP SAXParserFactory and configure it
              SAXParserFactory saxFactory = SAXParserFactory.newInstance();
              saxFactory.setNamespaceAware(isNameSpaceAware);
              saxFactory.setValidating(isValidating);
              // Create a JAXP SAXParser
              parser = saxFactory.newSAXParser();
              // Get the encapsulated SAX XMLReader
              reader = parser.getXMLReader();
              // Set the ErrorHandler
    This method is used to collect the user details.
         public Event getEvent(
              String newsXML,
              XMLHandler xmlHandler,
              IWDMessageManager mgr)
              throws SAXException, ParserConfigurationException, IOException {
              //create the parser, if not already done
              if (parser == null) {
                   this.createParser();
              //set the parser handler to extract the
              reader.setErrorHandler(xmlHandler);
              reader.setContentHandler(xmlHandler);
              InputSource source =
                   new InputSource(new ByteArrayInputStream(newsXML.getBytes()));
              reader.parse(source);
              //return the results of the parse           
              return xmlHandler.getEvent(mgr);
    Code for XMLHandler:-
    Created on Apr 12, 2006
    Author-Anish
    This is a parser class
    package com.idb.events.util;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import com.idb.events.Event;
    Created on Apr 12, 2006
    Author-Anish
    *This handler class is created to have constant value for variables and function for get events,
        character values for bean variable,
        parsing thr date ......etc
    package com.idb.events.util;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import java.util.*;
    import com.idb.events.Event;
    import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
    public class XMLHandler extends DefaultHandler {
         private static final String TITLE = "title";
         private static final String ORGANIZER = "organizer";
         IWDMessageManager manager;
         private Event events;
         private String tagName;
         public void setManager(IWDMessageManager mgr) {
              manager = mgr;
    This function is created to get events
         public Event getEvent(IWDMessageManager mgr) {
              manager = mgr;
              return this.events;
    This function is created to get character for setting values through event's bean setter method
         public void characters(char[] charArray, int startVal, int length)
              throws SAXException {
              String tagValue = new String(charArray, startVal, length);
              if (TITLE.equals(this.tagName)) {
                   this.events.setTitle(tagValue);
              if (ORGANIZER.equals(this.tagName)) {
                   String orgName = tagValue;
                   try {
                        orgName = getOrgName(orgName);
                   } catch (Exception ex) {
                   this.events.setOrganizer(orgName);
    This function is created to parse boolean.
         private final boolean parseBoolean(String inputBooleanStr) {
              boolean b;
              if (inputBooleanStr.equals("true")) {
                   b = true;
              } else {
                   b = false;
              return b;
    This function is used to call the super constructor.
         public void endElement(String uri, String localName, String qName)
              throws SAXException {
              super.endElement(uri, localName, qName);
         /* (non-Javadoc)
    @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
    This function is used to call the super constructor.
         public void fatalError(SAXParseException e) throws SAXException {
              super.fatalError(e);
    This function is created to set the elements base on the tag name.
         public void startElement(
              String uri,
              String localName,
              String qName,
              Attributes attributes)
              throws SAXException {
              this.tagName = localName;
              if (ROOT.equals(tagName)) {
                   this.events = new Event();
         public static void main(String a[]) {
              String cntry = "Nigeria";
              XMLHandler xml = new XMLHandler();
              ArrayList engList = new ArrayList();
              engList = xml.getCountries();
              ArrayList arList = xml.getArabicCountries();
              int engIndex = engList.indexOf(cntry);
              System.out.println("engIndex  :: " + engIndex);
              String arCntryName = (String) arList.get(engIndex);
              System.out.println(
                   ">>>>>>>>>>>>>>>>>>>>" + xml.getArabicCountryName(cntry));
    Hope that may help you.
    If need any help , you are most welcome.
    Regards,
    Deepak

  • Edit an XML file with SAX

    Dear all, I am so confused�.
    I have been trying for the last few days to understand how sax works� The only thing I understood is:
    DefaultHandler handler = new Echo01();
    SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                out = new OutputStreamWriter(System.out, "UTF8");
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse(file , handler);
            } catch (Throwable t) {
                t.printStackTrace();
            System.exit(0);
        }Ok, I assign the SAXParser the xml file and a handler. The parser parses and throws events that the handler catches. By implementing some handler interface or overriding the methods of an existing handler (e.g DeafultHandler class) I get to do stuff�
    But still, suppose I have implement startElement() method of DefaultHandler class and I know that the pointer is currently placed on an element e.g. <name>bob</name>. How do I get the value of the element, and if I manage to do that, how can I replace�bob� with �tom�?
    I would really appreciate any help given� just don�t recommend http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/ because although there are interesting staff in there, it does not solve my problem�

    Maybe SAX is not the right tool for you.
    With SAX, you implement methods like startElement and characters that get called as XML data is encountered by the parser. If you want to catch it or not, the SAX parser does not care. In your case, the "bob" part will be passed in one or more calls to characters. To safely process the data, you need to do something like build a StringBuffer or StringBuilder in the constructor of the class, and then in the startElement, if the name is one you want to read, set the length to zero. In the characters method, append the data to the StringBuilder or StringBuffer. In the endElement, do a toString to keep the data wherever you want.
    This works for simple XML, but may need to be enhanced if you have nested elements with string values that contain other elements.
    On the other hand, if your file is not huge, you could use DOM. With DOM, (or with JDOM, and I would expect with Dom4J -- but I have only used the first two) you do a parse and get a Document object with the entire tree. That allows you to easily (at least it is easy once you figure out how to do it) find a node like the "name" element and change the Text object that is its child from a value of "bob" to "tom". With DOM, you can then serialize the modified Document tree and save it as an XML file. SAX does not have any way to save your data. That burden falls to you entirely.
    Dave Patterson

  • Create XML file with worksheet's dynamically assigned through XSLT

    Hi all
    I have a requirement to create a xml file with worksheets dynamically created based on a field value in the internal table .
    I have all my values in internal table,  and am calling the transformation from bsp application.
    Say the internal table has field dataxyz, for every change in value in this field dataxyz  i need to create separate worksheet and populate that sheet with some corresponding values .
    please guide me how to create worksheet dynamically.
    thanks in advance.
    Bharathy
    Edited by: elam.bharathy on May 16, 2011 6:51 AM

    Can you use a schema when we compose XML doc from Database tables?
    Actually, I'm using SQL Server (sorry, wrong forum). But, I thought a Java tool would have a solution for me.

  • How to create multiple files with Receiver File Adapter in SAP PI 7.31 Java Stack

    Dear Friends,
    I am using Sender JDBC Adapter and Receiver File Adapter in Integration Flow in SAP PI 7.3 EHP 1 SP08 Java Stack environment. The requirement is that we need to create multiple files based on the row count in jdbc resultset. If there are 5 rows in resultset, we need to create 5 XML files with one row elements in one file. Similarly if there are 10 rows, we need to create 10 XML files.
    So how can we create multiple files in this scenario. I tried placing a for loop in the Java Mapping as below in the transform method:
    DynamicConfiguration conf = arg0.getDynamicConfiguration();
    StringBuffer sbFileData = new StringBuffer();
    for (int i =0; i < record.size(); i++ {
         . // Create XML for each row and Marshal the object into to the String Buffer
         String strFileName = "DC_" + new SimpleDateFormat("ddMMyyyyHHmm").format(new java.util.Date())+"_"+i+".xml";
         conf.put(KEY_FILENAME, strFileName);
         arg1.getOutputPayload().getOutputStream().write(sbFileData.toString().getBytes("UTF-8"));
         arg1.getOutputPayload().getOutputStream().flush();
    So here I'm flushing the OutputStream for each record. But it's not creating the multiple file, instead it creates only one file will all record XMLs appended to each other.
    Please let me know if I missing something or need to do some thing else.
    Regards,
    Shreyansh Shah

    Hi
    You can easily achieve this using graphical mapping.  Create your target message type like below
    MT_Target
      Details  0 to 1
          Data  0 to 1
    Source sample structure
    <resultset>
    <row>
    <column-name>column-value</ column-name>
    </row>
    Then do the message mapping like below
    map <row> with  MT_Target
    contant ----> Deatils
    column-name ------>Data
    In the signature tab of message mapping, choose the occurrence of your target message type as
    0 to unbounded.
    This will generate multiple files from multiple rows.
    Let me know if you have any doubt.

  • SQL Error : missing expression - Creating XML file with ODI

    Hi,
    I saw threads about errors like this and read that maybe it can come from how I chose the staging area. I still can't see where the problem is. I'm trying to create an xml file from data stored in a Oracle database. The interface which execution fails select data from tables and create a tag in the XML file. Here are information about it :
    The staging area is diferent from the target and is an oracle database schema. (I guess it creates temporary tables in that schema ?)
    In the flow tab, the LKM is LKM SQL to SQL, the option delete temporary objects is set to yes.
    The IKM choice for the target is IKM SQL Control Append and options are as following :
    - insert : yes
    - commit : yes
    - flow contreol : no
    - recycle errors : no
    - static control : no
    - truncate : no
    - delete all : no
    - create target table : yes
    - delete temporary objects : yes
    Columns mapping in the target are the following :
    WKID        >     THEADER.WKID
    EXTID        >     THEADER.EXTID
    ORDER     >     THEADER.ORDER
    INSTFK     >     THEADER.INSTFK
    For every column in the target :
    - Run on source
    - Updating : insert, update and ud4 are checked
    no update key is defined
    In the operator, the step failing when running the interface is the loading data in the work table.
    If you need the SQL request in the execution plan, or anything else, please tell me.
    Thank you in advance for any help on this.
    Marie

    It would help if you provide error message and its stack trace.
    Please also look at the documentation (If not already done so) for creating xml file XML Files - 11g Release 1 (11.1.1)

  • How to create xml file through SDK?

    Hi,
    I need help in creating the xml file using SAP B1 SDK?
    i want to create xml file which is in tally xml format.
    Warm Ragards,
    Mahendra

    Hi Mahendra,
    This is an example to save a form as XML :
    try
                    System.Xml.XmlDocument oXmlDoc = null;
                    string sXmlString = null;
                    oXmlDoc = new System.Xml.XmlDocument();
                    // get the form as an XML string
                    sXmlString = Form.GetAsXML();
                    // load the form's XML string to the
                    // XML document object
                    oXmlDoc.LoadXml(sXmlString);
                    string sPath = null;
                    sPath = System.IO.Directory.GetParent(System.Windows.Forms.Application.StartupPath).ToString();
                    sPath = System.IO.Directory.GetParent(sPath).ToString();
                    // save the XML Document
                    oXmlDoc.Save((sPath + @"\Form" + sType + ".xml"));
                    //oXmlDoc.Save(DIRECTORY_TEMPLATE + "Form" + sType + ".xml");
                catch (Exception ex)
                    SBO_Application.MessageBox("ERROR in 'SaveAsXML()' : " + ex.Message, 1, "Ok", "", "");
    And an example to navigate in the XML file :
    System.Xml.XmlDocument xxml;
                                    System.Xml.XmlNode node;
                                    System.Xml.XmlNodeList nodes;
                                    xxml = new System.Xml.XmlDocument();
                                    xxml.LoadXml(oRecAU.GetAsXML());
                                    nodes = xxml.SelectNodes("BOM/BO/IFC_AU/row");
                                    foreach (System.Xml.XmlNode node in nodes)
                                        oColumn.ValidValues.Add(node.SelectSingleNode("Code").InnerText, node.SelectSingleNode("Name").InnerText);
    I hope it's help you.
    Regards
    Michael

  • What's the best way to create XML file with a schema from a database table?

    Hi,
    I want to create an XML file from a database table (which has over 600 columns) using XML schema (.xsd file). I want to know the best way to do this.
    The output XML file is NOT a direct data dump from the DB table, there�re some logic around it, such as the XML file has some hierarchy with repeating tags.
    I have done this using JAXB by creating Java classes form XML schema, but I don�t want to map 600 DB columns to these Java classes manually, and loop through the record set to create repeating tags.
    I know there are few tools around now like MapForce (Altova), how do people do these now?
    Thanks,
    Chandi

    Can you use a schema when we compose XML doc from Database tables?
    Actually, I'm using SQL Server (sorry, wrong forum). But, I thought a Java tool would have a solution for me.

  • Create XML file with oracle DDL information

    Hi,
    I am working on a architecture where I was asked to see find the solution for the following issue:
    we are building a ODS which gets a feed from an ORACLE source. But ODS will not have any access to that table and the data will be pushed by source system. The requirement is whenever the source system change the table structure (add a column,drop a column, change data type) that should be reflected in ODS stage table by droping and recreating a table with the structure that comes everyday from the source. My question is without getting the DDL file from the source, can we get the structure in XML file along with data? so that I can use the XML file to create the stage table everyday in ODS. I dont' want to use xmltype or clob/varchar2. The oracle table should be rows and column.
    I know XML SQL will be able to insert the xml to oracle table and oracle table can be extracted to XML type.
    Thanks,
    Partha.

    Hi,
    If you need to create a new command, you can use SAP Developer Studio. After deploy you will see it in
    System administration->system configuration->cm->user interface->Commands.
    There are examples about how to create commands.
    You need to create your own layout set. This one use a resource renderer, here you must setup the commands group that you created.
    After that, you create a navigation iview and layout set field you setup your layout set.
    Patricio.

  • Create XML File with codepage (not UNICODE)

    Hi all ,
    I'm using the SDIXML_DATA_TO_DOM function module to create a xml format from an internal table, finally I write the internal table in xml format to file in the application server.
    Finally I get a file in XML format in UTF-8 (UNICODE), but I have to convert the UTF-8 into other codepage because the file is send to other system which not familiar with the UNICODE.
    Does anyone knows how to convert the codepage for the xml internal table ?
    Thanks,
    Yaki

    Another option rather than converting it after the fact is to have it create the XML file in the encoding that you want to begin with.  It looks like this function module you mention will either accept a pointer to a XML document object or create one for you.  I would suggest that you go ahead and create a document yourself and pass it to the function module.
      ixml = cl_ixml=>create( ).
      document = ixml->create_document( ).
    You can then call the method SET_ENCODING of the class IF_IXML_DOCUMENT.  The encoding itself is another class of type IF_IXML_ENCODING.  You can set the character set in this object using method SET_CHARACTER_SET.

Maybe you are looking for

  • Linked images in eps files

    I was playing with CS5 over the last several days and noticed somethng odd. - Place an image in a new Illustrator file. Your layers palette shows Layer 1 > Linked File. - Save a copy of that file as an eps. - Open the eps and look at the layers palet

  • JDBC- PI7.1- BAPI Synchronus

    Hi Experts, I have a scenario where Data of Sales orders are to be picked up from SQL Server using a STORED PROCEDURE and need to be sent to a BAPI -Sales Order which creates sales order in SAP ECC system and I would need to send the Sales ordenumber

  • Why N95-1(0534832) still do not have V30 FW

    Last month,i know that most N95 can be upgrade the firmware to V30 .Right now there is some people who live in Taiwan that they can upgrade their cell phone to v30.But the users who live in Hong Kong they can't. Anyone can tell me that how long do al

  • IMac + Xbox = PAIN

    Hey guys, looking for a little bit of help. I've Googled and Yahooed this - but haven't quite found what I'm looking for. (I should also state that I am a step or two above technically challenged. I can get something to work, but I usually need prett

  • QT Pro won't load

    I have just purchased QT Pro but the reg code will not load, it keps saying "invalid registartion" I have done everything from upper case, lowercase, hyphens, no hyphens, even cut and paste from their e-mail. any ideas