Create XML - DOM or SAX

I want to create a XML file from a table and store into predefined location. The total number of records are not more than 100.
I read about both technologies but which one i shld go for ?
Is it that for creaion go for DOM,
for parsing SAX (if not too much traversal) else DOM?
regards
Manisha

this really depends on what you are trying to accomplsh. If you are needing to use the data, then use the DOM. This will LOAD ALL the data into memory; may not be a problem with the small number of records (depending what is in the records). But then you have the tree to interact with.
If you simply need to react to the data as it is read, then parse the xml as it is read as perform the necessary actions.

Similar Messages

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

  • Creating XML DOM with Escape characters

    I am using DOM to generate xml fie. Setting some chinese character string which is hardcoded for one of node value.
    When i am setting value to xml node i am passing it as "∆" but DOM automatically converts this string and store into xml file as "&#x2206"
    Because of this i can not show proper chinese characters in PDF. How i can avoid this ? Is it possible to store chinese character as "&#x2206" itself inside xml?
    regards
    Manisha

    When setting the value from java you can use the real unicode character. Assuming with ࢞ you want to write the Unicode-Character at Codepoint 0x2206 you could just use "\u2206" in a java String to encode it. The XML library has to take care of how it's encoded in the final xml file.

  • How to Parse a string into an XML DOM ?

    Hi,
    I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?

    Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
    - Saish
    public final class DomParser extends Object {
         // Class Variables //
         private static final DocumentBuilder builder;
         private static final String JAXP_SCHEMA_LANGUAGE =
             "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         /** W3C schema definitions */
         private static final String W3C_XML_SCHEMA =
             "http://www.w3.org/2001/XMLSchema";
         // Constructors //
         static {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   builder = factory.newDocumentBuilder();
                   builder.setErrorHandler(new ErrorHandler() {
                       public void warning(SAXParseException e) throws SAXException {
                           System.err.println("[warning] "+e.getMessage());
                       public void error(SAXParseException e) throws SAXException {
                           System.err.println("[error] "+e.getMessage());
                       public void fatalError(SAXParseException e) throws SAXException {
                           System.err.println("[fatal error] "+e.getMessage());
                           throw new XmlParsingError("Fatal validation error", e);
              catch (ParserConfigurationException fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
              catch (FactoryConfigurationError fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
         private DomParser() {
              super();
         // Public Methods //
         public static final Document newDocument() {
              return builder.newDocument();
         public static final Document parseDocument(final InputStream in) {
              try {
                   return builder.parse(in);
              catch (SAXException e) {
                   throw new XmlParsingError("SAX exception during parsing.  Document is not well-formed or contains " +
                        "illegal characters", e);
              catch (IOException e) {
                   throw new XmlParsingError("Encountered I/O exception during parsing", e);
    }- Saish

  • Creation of xml dom

    hi
    i want to create xml dom in pl/sql . can i use dbms_xmlgen to create it?
    i have done using dbms_xmldom but in my work environment i cant use tht package.
    regards

    hi
    i want to create xml dom in pl/sql . can i use dbms_xmlgen to create it?
    i have done using dbms_xmldom but in my work environment i cant use tht package.
    regards

  • XML parser used in Oracle...DOM or SAX?

    Hi,
    My db version:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE    11.2.0.1.0    Production
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    Question:
    I get an XML feed and load it into a temporary table T1.
    My requirement is to load it in the exact sequence as I get the rows in xml and also populate a column in the temporary table as a sequence like 1 2 3 corresponding to the rows in the xml
    When I do load the xml, it gets loaded in same order the xml feed is sent. So no worries.
    But while I was researching I came to know that Oracle could use either DOM or SAX parser. If it uses SAX, then the order is maintained as in XML. But if DOM is used, the order wont be maintained.
    Please let me know, how I can ensure that the xml order is maintained as it is while loading into temp table.

    I apologize, here is more details
    {code}
    CREATE TABLE XMLTEMPTBL
      PARAM      NVARCHAR2(30 BYTE),
      PARAMORDERSEQ NUMBER(3)
    XML format:
    <?xml version="1.0"?>
    <ROWSET>
    <ROW>
    <PARAM1>abc</PARAM1>
    </ROW>
    <ROW>
    <PARAM2>def</PARAM2>
    </ROW> 
    <ROW>
    <PARAM3>ghi</PARAM3>
    </ROW> 
    <ROW>
    <PARAM4>jkl</PARAM4>
    </ROW>
    </ROWSET>
    PROCEDURE insertparams (p_xmldoc IN CLOB)
    IS    
      insctx   DBMS_XMLSTORE.ctxtype;
      ROWS     NUMBER;     
    BEGIN     
      /*inserting insdoc into a temp table*/
      insctx := DBMS_XMLSTORE.newcontext ('xmlTempTbl');
      ROWS := DBMS_XMLSTORE.insertxml (insctx, p_xmldoc);
      DBMS_XMLSTORE.closecontext (insctx);
    END;
    I want to insert into table this way:
    select * from xmltemptb;
    PARAM PARAMORDERSEQ
    abc 1
    def 2
    ghi 3
    jkl 4
    {code}
    My procedure is not 100% correct (but it gives an idea what code I am using to load into table), but I want to ensure the xml rows are loaded into the table in the same sequence.

  • How to remove element namespaces in XML file using DOM or SAX?

    Hi Guys,
    I developed a JAVA mapping in XI to add name spaces for XML file, after mapping,name spaces xmlns="http://www.mro.com/mx/integration" and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" were added correctly, but for some nodes, such as <Header> and <Content>, a name space xmlns="" was added automatically.Please check below files to compare.
    It looks like be added automatically by XI. I didn't process anything for these nodes in JAVA program.
    Now the issue is, how can I remove these redundant namespaces? Such as xmlns="".
    Can I remove them using DOM or SAX in JAVA Mapping?
    Thanks in advance.
    ====>Original XML file
    <?xml version="1.0" encoding="UTF-8"?>
    <LLYLPPInterface language="EN">
       <Header>
          <SenderID>GBIP</SenderID>
          <CreationDateTime>2008-02-13T22:49:34-05:00</CreationDateTime>
          <RecipientID/>
          <MessageID/>
       </Header>
       <Content>
          <LLY-LPP>
             <INVOICE>
                <INVOICELINE>
                   <PONUM>4780000008</PONUM>
                   <POLINENUM>1</POLINENUM>
                   <INVOICEQTY>1</INVOICEQTY>
                   <LOADEDCOST>68</LOADEDCOST>
                </INVOICELINE>
             </INVOICE>
          </LLY-LPP>
       </Content>
    </LLYLPPInterface>
    ===>Target XML file after JAVA mapping
    <?xml version="1.0" encoding="utf-8"?>
    <LLYLPPInterface language="EN" xmlns="http://www.mro.com/mx/integration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
         <Header xmlns="">
              <SenderID>GBIP</SenderID>
              <CreationDateTime>2008-02-13T23:11:55-05:00</CreationDateTime>
              <RecipientID/>
              <MessageID/>
         </Header>
         <Content xmlns="">
              <LLY-LPP>
                   <INVOICE>
                        <INVOICELINE>
                             <PONUM>4780000008</PONUM>
                             <POLINENUM>0</POLINENUM>
                             <INVOICEQTY>1</INVOICEQTY>
                             <LOADEDCOST>68</LOADEDCOST>
                        </INVOICELINE>
                   </INVOICE>
              </LLY-LPP>
         </Content>
    </LLYLPPInterface>
    Edited by: Eddie Zhang on Feb 14, 2008 9:22 AM
    Edited by: Eddie Zhang on Feb 14, 2008 9:24 AM

    Hi Milan,
    Thanks for your replay.
    Actually when I used module XMLAnonymizerBean to convert namespaces, the header of XML, such as <?xml version="1.0" encoding="UTF-8"?> was converted to format <?xml version='1.0' encoding='UTF-8'?>, quote was converted to single quote. Although I set parameter anonymizer.quote = ", it still didn't work, single quote appeared instead of quote.
    I'm not sure why this happened. Can anyone help to clarify this?
    Thanks
    Edited by: Eddie Zhang on Feb 15, 2008 2:11 AM

  • Filling tab of an XML document created by DOM

    have a problem with filling tab of an XML file created by DOM
    I used this code to create the document:
    public class DOMCreation {
    public void createDOM( String a, String b ) {
              Document doc = new DocumentImpl( null );
              // Il codice che segue � indipendente dal particolare parser utilizzato
              // Creazione dell'elemento root del documento, identificato dal tag <DOCUMENT>
              Element root = doc.createElement("DOCUMENT");
              doc.appendChild(root);
              // Creazione ed inserimento di un nodo
              Element element1 = doc.createElement("USERNAME");
              root.appendChild( element1 );
              // Creazione ed inserimento di un secondo nodo discendente di <DOCUMENT>
              root.appendChild( doc.createElement("PIN") );
    System.out.println( a );
    System.out.println( b );
              try {
                   serializeDocument( doc, new FileOutputStream("d:/doc.xml"));
              } catch (FileNotFoundException e) {}
    private static void serializeDocument(Document doc, OutputStream output) {
              try {
                   DOMSerializer ser = new XMLSerializer( output, null);
                   ser.serialize(doc);
              } catch (IOException e) {
                   System.err.println("I/O exception while serializing document: " + e.getMessage());
    }

    The code lines:
    System.out.println( a );
    System.out.println( b );
    had the purpose to check if these two parameters were passed by another procedure. These two parameters, however, represent the content to be filled in the tag of XML document created by DOM.
    About the other question on "what parser do you use", I'm using Apache's Xerces. However that's the "import" that I include in this procedure:
    import org.apache.xerces.dom.DocumentImpl;
    import org.apache.xerces.dom.NodeIteratorImpl;
    import org.apache.xml.serialize.*;
    import org.w3c.dom.*;
    import org.w3c.dom.traversal.*;
    import java.io.*;

  • Printing XML DOM to string

    When I create an xml document and print it to a string I find that I can only get 900 characters at a time from the output string (using substring) even though its length is reported as > 900
    Running on Oracle 8.1.7

    Sun's resources on XML (including JAXP):
    http://java.sun.com/xml/
    Parser with DOM and SAX support:
    http://xml.apache.org/xerces-j/
    http://www.alphaworks.ibm.com/tech/xml4j
    Of other interest:
    http://xml.apache.org/xalan/
    http://java.apache.org/ecs/index.html
    http://xml.apache.org/cocoon/index.html
    Cameron Purdy
    http://www.tangosol.com
    "Kevin Woo" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    Would anyone know where I could get a XML DOM to Java String parser,
    which does forward and backward parsing?
    Thanks a bunch,
    Kevin Woo

  • How to SAVE a updated XML DOM Data to the file?

    Hi
    I am able to load an XML file into a XML DOM object using JAVA (xerces). I have update the required data in the DOM.
    But I am NOT able to save back the data to the physical file.
    Will appreciate if you can help me ASAP.

    Hi Krishar,
    Check out the jaxp new release on java.sun.com. This api has classes and methods to help you do the same.
    sample code:
         try
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              java.net.URL url = this.getClass().getResource(XML_FILE);
              java.io.File thsFile = new java.io.File(url.getFile());
              DocumentBuilder builder = factory.newDocumentBuilder();
              TransformerFactory tFactory = TransformerFactory.newInstance();
              Transformer transformer = tFactory.newTransformer();
              document = builder.parse(thsFile);
    //You can do any modification to the document here
              DOMSource source = new DOMSource(document);
              StreamResult result = new StreamResult(thsFile);
              transformer.transform(source, result);
         catch (TransformerConfigurationException tce)
              System.out.println("\n** Transformer Factory error");
              System.out.println(" " + tce.getMessage());
              Throwable x = tce;
              if (tce.getException() != null)
                   x = tce.getException();
              x.printStackTrace();
         catch (TransformerException te)
              System.out.println("\n** Transformation error in add:");
              System.out.println(" " + te.getMessage());
              Throwable x = te;
              if (te.getException() != null)
                   x = te.getException();
              x.printStackTrace();
         catch (SAXException sxe)
              System.out.println("sax exp" + sxe.getMessage());
         catch (Exception ex)
              System.out.println("exc exp" + ex);
              ex.printStackTrace();
    Hope this will help you XML_FILE is constant representing the path of the file. It should be in classpath. The program essentially parsing a xml file and creating dom document and then writing it back to the same file. you can do any modifications/write to other file etc...
    Think this will suffice your requirement
    bye
    take care
    Hi
    I am able to load an XML file into a XML DOM object
    using JAVA (xerces). I have update the required data
    in the DOM.
    But I am NOT able to save back the data to the
    physical file.
    Will appreciate if you can help me ASAP.

  • DOM or SAX?

    Hi,
    I have a very simple XML document as below:
    <message>
    <content></content>
    <date></date>
    </message>
    All I want to do is retrieve the <content> and <date> elements. Should I be looking at using DOM or SAX?
    Thanks.

    public class MyParser extends DefaultHandler{
       private String content;    // to hold the content value
       private String date;       // to hold the date value
       private String nodeName;   // to hold the nodeName
       // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       public MyParser(){ }
       // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       public void parse(String xmldoc){
          try{
              XMLReader reader = XMLReaderFactory.createXMLReader(vendor);
              reader.setContentHandler(this);
              // for xml document pass in as a String
              InputSource inputSource = new InputSource(
                                         new StringReader(xmldoc));
              reader.parse(inputSource); 
              // comment out InputSource if you use a file instead and
              // change reader.parse(inputsource) to reader.parse(xmldoc)
          catch (Exception e) { System.out.println(e); }
          // you would probably be catching SAXException and IOException
          // but i use this to make it simplier
       // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       public void startElement(String ns, String name, String qName,
                                Attributes atts) throws SAXException {
           nodeName = name;
       // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       public void characters(char[] ch, int start, int length)
                                          throws SAXException {
          if (nodeName.equals("content")
              content += new String(ch, start, length);
          else if (nodeName.equals("date")
              date += new String(ch, start, length);
       // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        public void endElement(String ns, String name, String qName)
                                               throws SAXException {
            if (name.equals("content"){
                   System.out.println("Content value is = " + content);
                content = ""; 
            else if (name.equals("date")){
                   System.out.println("Date value is = " + date);
                date = "";
            else if (name.equals("message")){
                System.out.println("End of XML doc and end of parsing");
    }Many people use a boolean to save the where they are at (in the xml doc)
    But since your xml doc is simple, it's not necessary
    Also...If the content value is a long string..I would use a StringBuffer
    instead of String (because the SAX Parser can call on the character() method multiple time...Normally, it only call on it once. Using StringBuffer reduce Object creating and reduce garbage collection.

  • 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

  • Heap space error while creating XML document from Resultset

    I am getting Heap space error while creating XML document from Resultset.
    It was working fine from small result set object but when the size of resultset was more than 25,000, heap space error
    I am already using -Xms32m -Xmx1024m
    Is there a way to directly write to xml file from resultset instead of creating the whole document first and then writing it to file? Code examples please?
    here is my code:
    stmt = conn.prepareStatement(sql);
    result = stmt.executeQuery();
    result.setFetchSize(999);
    Document doc = JDBCUtil.toDocument(result, Application.BANK_ID, interfaceType, Application.VERSION);
    JDBCUtil.write(doc, fileName);
    public static Document toDocument(ResultSet rs, String bankId, String interfaceFileType, String version)
        throws ParserConfigurationException, SQLException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            Element results = doc.createElement("sims");
            results.setAttribute("bank", bankId);
            results.setAttribute("record_type", "HEADER");
            results.setAttribute("file_type", interfaceFileType);
            results.setAttribute("version", version);
            doc.appendChild(results);
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            String columnName="";
            Object value;
            while (rs.next()) {
                Element row = doc.createElement("rec");
                results.appendChild(row);
                for (int i = 1; i <= colCount; i++) {
                    columnName = rsmd.getColumnLabel(i);
                    value = rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    if(value != null)
                        node.appendChild(doc.createTextNode(value.toString()));
                    else
                        node.appendChild(doc.createTextNode(""));
                    row.appendChild(node);
            return doc;
    public static void write(Document document, String filename) {
            //long start = System.currentTimeMillis();
            // lets write to a file
            OutputFormat format = new OutputFormat(document); // Serialize DOM
            format.setIndent(2);
            format.setLineSeparator(System.getProperty("line.separator"));
            format.setLineWidth(80);
            try {
                FileWriter writer = new FileWriter(filename);
                BufferedWriter buf = new BufferedWriter(writer);
                XMLSerializer FileSerial = new XMLSerializer(writer, format);
                FileSerial.asDOMSerializer(); // As a DOM Serializer
                FileSerial.serialize(document);
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            //long end = System.currentTimeMillis();
            //System.err.println("W3C File write time :" + (end - start) + "  " + filename);
        }

    you can increase your heap size..... try setting this as your environment variable.....
    variable: JAVA_OPTS
    value: -Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m

  • Performance problem when creating XML-file

    Hi,
    I want to create a XML-file with customer data from an internal table. This internal table has appr. 62000 entries. It takes hours to create the elements of the file.
    This is the coding I have used:
      loop at it_debtor.
        at first.
        Creating a ixml factory
          l_ixml = cl_ixml=>create( ).
        Creating the dom object model
          l_document = l_ixml->create_document( ).
        Fill root node
          l_element_argdeb  = l_document->create_simple_element(name = 'argDebtors'
                      parent = l_document ).
        endat.
      Create element 'debtor' as child of 'argdeb'
        l_element_debtor  = l_document->create_simple_element(
                     name = 'debtor'
                   parent = l_element_argdeb ).
      Create elements as child of 'debtor'
        l_value = it_debtor-admid.
        perform create_element using 'financialAdministrationId'.
        l_value = it_debtor-kunnr.
        perform create_element using 'financialDebtorId'.
        l_value = it_debtor-name1.
        21 child elements in total are created
      endloop.
      Creating a stream factory
      l_streamfactory = l_ixml->create_stream_factory( ).
      Connect internal XML table to stream factory
      l_ostream = l_streamfactory->create_ostream_itable( table =
      l_xml_table ).
      Rendering the document
      l_renderer = l_ixml->create_renderer( ostream  = l_ostream
                                          document = l_document ).
      l_rc = l_renderer->render( ).
      open dataset p_path for output in binary mode.
      if sy-subrc eq 0.
        loop at l_xml_table into rec.
          transfer rec to p_path.
        endloop.
        close dataset p_path.
        if sy-subrc eq 0.
          write:/ wa_lines, 'records have been processed'.
        endif.
      else.
        write:/ p_path, 'can not be opened.'.
      endif.
    form create_element using    p_text.
      check not l_value is initial.
      l_element_dummy  = l_document->create_simple_element(
                    name = p_text
                    value = l_value
                    parent = l_element_debtor ).
                                                                                    endform.                    " create_element
    Please can anyone tell me how to improve the performance.
    The method create_simple_element takes a long time.
    SAP release : 46C
    Regard,
    Christine

    Hi Christine!
    There might be several reasons - but you have to look at the living patient, not only the dead coding.
    You did not show any selects, loop at ... where or read table statements -> the usual slow parts are not included (or visible...).
    Of course the method-calls can contain slow statements, but you can also have problems because of size (when internal memory gets swaped to disc).
    Make a runtime analysis (SE30), have a look in SM50 (details!) for the size, maybe add an info-message for every 1000-customer (-> will be logged in job-log), so you will see if all 1000-packs are executed in same runtime.
    With this tools you have to search for the slow parts:
    - general out of memory problems, maybe because of to much buffering (visible by slower execution at the end)
    - slow methods / selects / other components by SM30 -> have a closer look
    Maybe a simple solution: make three portions with 20000 entries each and just copy the files into one, if necessary.
    Regards,
    Christian

  • Creating XML File Using xmldom Package

    How can I create an XML file from scratch using the PL/SQL xmldom package?
    I want to create an XML file using the xmldom package instead of building the individual tags as strings of VARCHAR2 character data. There is quite a bit of documentation regarding manipulating input XML files using DOM -- but not for creating XML files from scratch given known "tagnames" (<lastName>) and retrieved database "values" ("Smith").
    <person>
    <lastName>Smith</lastName>
    </person>
    Is there any documentation that you can recommend?
    Thank you.

    Here is an example.
    The create_file procedure creates the file.
    The other procedures are generic procs that can be used with any XML.
    PROCEDURE create_file_with_root(po_xmldoc OUT xmldom.DOMDocument,
    pi_root_tag IN VARCHAR2,
                                            po_root_element OUT xmldom.domelement,
                                            po_root_node OUT xmldom.domnode,
                                            pi_doctype_url IN VARCHAR2) IS
    xmldoc xmldom.DOMDocument;
    root xmldom.domnode;
    root_node xmldom.domnode;
    root_element xmldom.domelement;
    record_node xmldom.domnode;
    newelenode xmldom.DOMNode;
    BEGIN
    xmldoc := xmldom.newDOMDocument;
    xmldom.setVersion(xmldoc, '1.0');
    xmldom.setDoctype(xmldoc, pi_root_tag, pi_doctype_url,'');
    -- Create the root --
    root := xmldom.makeNode(xmldoc);
    -- Create the root element in the file --
    create_element_and_append(xmldoc, pi_root_tag, root, root_element, root_node);
    po_xmldoc := xmldoc;
    po_root_node := root_node;
    po_root_element := root_element;
    END create_file_with_root;
    PROCEDURE create_element_and_append(pi_xmldoc IN OUT xmldom.DOMDocument,
    pi_element_name IN VARCHAR2,
                                            pi_parent_node IN xmldom.domnode,
                                            po_new_element OUT xmldom.domelement,
                                            po_new_node OUT xmldom.domnode) IS
    element xmldom.domelement;
    child_node xmldom.domnode;
    newelenode xmldom.DOMNode;
    BEGIN
    element := xmldom.createElement(pi_xmldoc, pi_element_name);
    child_node := xmldom.makeNode(element);
    -- Append the new node to the parent --
    newelenode := xmldom.appendchild(pi_parent_node, child_node);
    po_new_node := child_node;
    po_new_element := element;
    END create_element_and_append;
    FUNCTION create_text_element(pio_xmldoc IN OUT xmldom.DOMDocument, pi_element_name IN VARCHAR2,
    pi_element_data IN VARCHAR2, pi_parent_node IN xmldom.domnode) RETURN xmldom.domnode IS
    parent_node xmldom.domnode;                                   
    child_node xmldom.domnode;
    child_element xmldom.domelement;
    newelenode xmldom.DOMNode;
    textele xmldom.DOMText;
    compnode xmldom.DOMNode;
    BEGIN
    create_element_and_append(pio_xmldoc, pi_element_name, pi_parent_node, child_element, child_node);
    parent_node := child_node;
    -- Create a text node --
    textele := xmldom.createTextNode(pio_xmldoc, pi_element_data);
    child_node := xmldom.makeNode(textele);
    -- Link the text node to the new node --
    compnode := xmldom.appendChild(parent_node, child_node);
    RETURN newelenode;
    END create_text_element;
    PROCEDURE create_file IS
    xmldoc xmldom.DOMDocument;
    root_node xmldom.domnode;
    xml_doctype xmldom.DOMDocumentType;
    root_element xmldom.domelement;
    record_element xmldom.domelement;
    record_node xmldom.domnode;
    parent_node xmldom.domnode;
    child_node xmldom.domnode;
    newelenode xmldom.DOMNode;
    textele xmldom.DOMText;
    compnode xmldom.DOMNode;
    BEGIN
    xmldoc := xmldom.newDOMDocument;
    xmldom.setVersion(xmldoc, '1.0');
    create_file_with_root(xmldoc, 'root', root_element, root_node, 'test.dtd');
    xmldom.setAttribute(root_element, 'interface_type', 'EXCHANGE_RATES');
    -- Create the record element in the file --
    create_element_and_append(xmldoc, 'record', root_node, record_element, record_node);
    parent_node := create_text_element(xmldoc, 'title', 'Mr', record_node);
    parent_node := create_text_element(xmldoc, 'name', 'Joe', record_node);
    parent_node := create_text_element(xmldoc,'surname', 'Blogs', record_node);
    -- Create the record element in the file --
    create_element_and_append(xmldoc, 'record', root_node, record_element, record_node);
    parent_node := create_text_element(xmldoc, 'title', 'Mrs', record_node);
    parent_node := create_text_element(xmldoc, 'name', 'A', record_node);
    parent_node := create_text_element(xmldoc, 'surname', 'B', record_node);
    -- write the newly created dom document into the buffer assuming it is less than 32K
    xmldom.writeTofile(xmldoc, 'c:\laiki\willow_data\test.xml');
    EXCEPTION
    WHEN xmldom.INDEX_SIZE_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Index Size error');
    WHEN xmldom.DOMSTRING_SIZE_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'String Size error');
    WHEN xmldom.HIERARCHY_REQUEST_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Hierarchy request error');
    WHEN xmldom.WRONG_DOCUMENT_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Wrong doc error');
    WHEN xmldom.INVALID_CHARACTER_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Invalid Char error');
    WHEN xmldom.NO_DATA_ALLOWED_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Nod data allowed error');
    WHEN xmldom.NO_MODIFICATION_ALLOWED_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'No mod allowed error');
    WHEN xmldom.NOT_FOUND_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Not found error');
    WHEN xmldom.NOT_SUPPORTED_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'Not supported error');
    WHEN xmldom.INUSE_ATTRIBUTE_ERR THEN
    RAISE_APPLICATION_ERROR(-20120, 'In use attr error');
    WHEN OTHERS THEN
    dbms_output.put_line('exception occured' || SQLCODE || SUBSTR(SQLERRM, 1, 100));
    END create_file;

Maybe you are looking for