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

Similar Messages

  • 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}

  • How to create nested xml tags using java parser?

    Hi,
    I need to create a xml file containing following tags using java program-
    <A attr1="abc">
    <B attr2="xyz">
    <C attr3="pqr"> </C>
    </B>
    </A>
    Can anyone please let me know which parser should I use to create the above mentioned xml file?
    If possible, please post a code snippet for the same.
    Thanks in advance..

    Well, you could start by doing it all the 'old fashioned' way; create a String object containing that text and then write it away to a file. Or you could take the time to look at the javadoc for all of the xml support that the Java language itself supplies - XMLReader/Writer for a start. After that put together some code that you think would do the job and ask for help on any specific problems you encounter.

  • Updating XML file using DOM parser

    Hi,
    Can someone help me, how to update following XML file using DOM parser.
    The following is my XML file.
    <students>
         <student>
              <id>1</id>
              <name>abc</name>
         </student>
         <student>
              <id>2</id>
              <name>xyz</name>
         </student>
         <student>
              <id>3</id>
              <name/>
         </student>
         <student>
              <id>4</id>
              <name>ijk</name>
         </student>
         <student>
              <id>5</id>
              <name></name>
         </student>
    </students>Consider, I will input 2 fields, ie., id & name. For the matching Id, the name has to be updated.
    Though, I have achieved this, but I am unable to update the value for 3rd record, & 5th record ie., id=3 & id=5. Since, these are blank.
    Thanks.

    Some <name> elements have a child node which is a text node. From what you say it appears you know how to change those text nodes.
    The other <name> elements don't have any child nodes. But you want one. This suggests to me that you need code that creates a text node and adds it to the <name> element as its child.

  • How can we get  tag of XML file using SAX

    Hi ,
    I'm parsing one SAX parser , I'have almost done this parsing. i have faced problem for one case, i'e how can we get tag from XML file using SAX parser?
    XML file is
    <DFProperties>
    <AccessType>
    <Get/>
    </AccessType> <Description>
    gdhhd
    </Description>
    <DFFormat>
    <chr/>
    </DFFormat>
    <Scope>
    <Permanent/>
    </Scope>
    <DFTitle>gsgd</DFTitle>
    <DFType>
    <MIME>text/plain</MIME>
    </DFType>
    </DFProperties>
    I want out like GET and Permanent... means this one tag which is present inside of another tag.
    Handler class like
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if(_ACCESSTYPE.equals(localName)){
                   accessTypeElement=ACCESSTYPE;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_ACCESSTYPE.equals(_accessTypeElement)) {
                   String strValue = new String(ch, start, length);
                   System.out.println("Accestype-----------------------------> " + strValue);
                   //System.out.println(" " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_ACCESSTYPE.equals(localName)) {
                   _accessTypeElement = "";
    . please any body help me

    Hi ,
    I have one problem,Please help me.
    1. How can I'll identify where exactly my Node is ended,means how how can we find corresponding nodename? in partcular place
    <Node> .............starttag1
    <NodeName>Test</NodeName>
    <Node>................starttag2
    <nodeName>test1</NodeName>
    </Node>..................endtag2
    <Node>.....................starttag3
    <NodeName><NodeName>
    <Node> .........................starttag4
    <NodeName>test4</NodeName>
    </Node>.......enddtag4
    </Node>...........end tag3
    </Node>............endtag1
    my code is below
    private final String _NODENAME = "NodeName";
    private final String _NODE = "Node";
    private String _nodeElement = "";
         private String _NodeNameElement = "";
    public void startElement(String namespaceURI, String localName,
                   String qName, Attributes atts) throws SAXException {
    if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    if(_NODE.equals(localName)){
         System.out.println("start");
         if (_NODENAME.equals(localName)) {
                   NodeNameElement = NODENAME;
    public void characters(char[] ch, int start, int length)
                   throws SAXException {
    if (_NODENAME.equals(_NodeNameElement)) {
                   String strValue = new String(ch, start, length);
                   String sttt=strValue;
                   System.out.println("NODENAME: ************* " + strValue);
    if(_NODE.equals(_nodeElement)){
                   if (_NODENAME.equals(_NodeNameElement)) {
                        String strValue = new String(ch, start, length);
                        String sttt=strValue;
                        System.out.println("nodevalue********** " + strValue);
    public void endElement(String namespaceURI, String localName, String qName)
                   throws SAXException {
    if (_NODENAME.equals(localName)) {
                   _NodeNameElement = "";
    if(_NODE.equals(localName)){
                   System.out.println("NODENAME: %%%%%%%%%");
    please help me. How can I figure node ending for particular nodename

  • 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

  • How to write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • Creating an XML file using Java Standalone

    Hi,
    My problem is -
    1) write a java stand alone retrieving data from database and put the data in XML format (i.e; we have to create an XML file).
    How to do this? Could any one of you please suggest me how to code or can i have any links that refer the code snippets.
    Thanks.

    Could someone give me a link with information on how SAX is used to create an XML?
    null

  • How to Update existing XML File Using Java Swing

    Hi,
    I am reading XML file and getting keywords into JList. When i add some keywords into JList through textfield and remove keywords JList, then after click on save button it should update xml file. How can i do it ?
    Please provide me some code tips for updating xml file
    This is the code that i am using for reading XML File:
    import javax.swing.*;
    import java.awt.event.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import java.io.IOException;
    import java.util.*;
    import java.text.Collator;
    import java.util.regex.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import com.cloudgarden.layout.AnchorConstraint;
    import com.cloudgarden.layout.AnchorLayout;
    public class getKeywords extends JFrame implements ActionListener
    static JPanel p;
    static JLabel lbl;
    static JButton btnSave,btnAdd,btnRemove;
    static String path;
    static Vector v;
    static JList lstCur;
    static JTextField txtKey;
    Document dom;
    static image imgval;
    NodeList nodelstImage;
    static AnchorLayout anchorLay;
    private DefaultListModel lstCurModel;
    public getKeywords()
         super("Current Keywords");
        v=new Vector();
        p=new JPanel();
        txtKey=new JTextField(10);
        btnAdd=new JButton("Add");
        btnRemove=new JButton("Remove");
        btnSave=new JButton("Save");
        lbl=new JLabel("Current Keywords");
        lstCurModel=new DefaultListModel();
            lstCur=new JList();
            JScrollPane scr=new JScrollPane(lstCur);
        runExample();
         lstCur.setModel(lstCurModel);
         p.add(lbl);
         p.add(scr);
         p.add(txtKey);
         p.add(btnAdd);
         p.add(btnRemove);
         p.add(btnSave);
         add(p);
         btnAdd.addActionListener(this);
         btnRemove.addActionListener(this);
         btnSave.addActionListener(this);
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    public static void main(String arg[])
         getKeywords g=new getKeywords();
         g.resize(250,400);
         g.setVisible(true);     
    public void actionPerformed(ActionEvent ae)
         if(ae.getSource()==btnAdd)
              lstCurModel.addElement(txtKey.getText());
         if(ae.getSource()==btnRemove)
              lstCurModel.remove(lstCur.getSelectedIndex());
         if(ae.getSource()==btnSave)
              //Code to Write
         public void runExample()
              //Parse the XML file and get the DOM object
              ParseXMLFile();
              //Get the Detail of the Image Document
              parseImageDocument();
              //Get the Detail of the LML Document
              //parseLMLDocument();
              //System.out.println(lmlval.Title);
         public void ParseXMLFile()
              //Get the Factory
              DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
              try
                   //Using factory get an instance of the Document Builder
                   DocumentBuilder builder = builderFac.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   dom = builder.parse("LML.xml");
              catch(ParserConfigurationException pce)
                   pce.printStackTrace();
              catch(SAXException sax)
                   sax.printStackTrace();
              catch(IOException ioex)
                   ioex.printStackTrace();
         public void parseImageDocument()
              //Get the root element
              Element docImgEle = dom.getDocumentElement();
              //Get a nodelist for <Image> Element
              nodelstImage =  docImgEle.getElementsByTagName("Image");
              if(nodelstImage != null && nodelstImage.getLength() > 0)
                   for(int i = 0; i < nodelstImage.getLength(); i++)
                        //Get the LML elements
                        Element el = (Element)nodelstImage.item(i);
                        //Get the LML object
                        getImage myImgval = new getImage();
                        imgval = myImgval.getimage(el);
                        v.addElement(new String(imgval.Thumb));
                        String[] x = Pattern.compile(",").split(imgval.Keys);
                        for (int s=0; s<x.length; s++)
                        lstCurModel.addElement(x[s].trim());
                        //System.out.println(x[s].trim());
    }     Thanks
    Nitin

    You should update your DOM document to represent the changes that you want made.
    Then, using the Transformation API you simply transform your document onto a stream representing your file. Something like this:
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    // TODO - set indentation amount!
    Source source = new DOMSource(dom);
    Result result = new StreamResult(file);
    transformer.transform(source, result);Hope this helps.

  • How do I generate XML File Using JDeveloper 9.0.3

    Hi All
    I want to generate a XML file against the data in one of my Oracle table,,,, This is the first time I am doing this Task, so please let me know whether I am going through the correct path, or if not appreciate if you could put me to the correct system of doing this please���..
    OK , Well I am working to a publishing company in Australia and we have Oracle 8i (Release 3 ) database and I have Oracle JDeveloper (9.0.3 -Preview ) version in my personal computer.
    I have a Table(ONIXT4) with three Columns( ISBN,Author,Price) in Oracle as follows:
    ISBN     Author     Price
    2512456321     Peter     14.50
    7445854127     Ray      21.75
    What I want to generate a XML File using JDeveloper as below with respect to data in above Table.
    <ISBN>2512456321</ISBN>
    <ProductInfor>
    <Author>Peter</Author>
    <Price>14.50</Price>
    </ProductInfor>
    <ISBN>7445854127</ISBN>
    <ProductInfor>
    <Author> Ray </Author>
    <Price>21.75</Price>
    </ProductInfor>
    I created the database connection within JDeveloper to Oracle those working fine,, my major problem is,, the Tag <ProductInfor>, since this is not a Column Name of the Table I don't know how should I incorporate this with the file.
    What I did so far with the JDeveloper:
    1.Create the Workspace and the Project
    2.File -- New -- XML -- XSQL
    3.Then I Selected Query from the Component Palette,, Property Values were NOT changed, and gave 'Select * from ONIXT4'
    Whole Untitled3.xsql file look likes below
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <!--
    | Uncomment the following processing instruction and replace
    | the stylesheet name to transform output of your XSQL Page using XSLT
    <?xml-stylesheet type="text/xsl" href="YourStylesheet.xsl" ?>
    -->
    <page xmlns:xsql="urn:oracle-xsql" connection="Connection1">
    <xsql:query max-rows="-1" null-indicator="no" tag-case="lower">
    Select * From OnixT4
    </xsql:query>
    </page>
    Then the Result comes as:
    <?xml version="1.0" encoding="windows-1252" ?>
    - <!--
    | Uncomment the following processing instruction and replace
    | the stylesheet name to transform output of your XSQL Page using XSLT
    <?xml-stylesheet type="text/xsl" href="YourStylesheet.xsl" ?>
    -->
    - <page>
    - <rowset>
    - <row num="1">
    <isbn>2512456321</isbn>
    <author>Peter</author>
    <price>14.5</price>
    </row>
    - <row num="2">
    <isbn>7445854127</isbn>
    <author>Ray</author>
    <price>21.75</price>
    </row>
    </rowset>
    </page>
    How do I format the outcome to obtain the my requirement??
    Welcome all comments of donig this ....

    To format your XML to the requiered output you'll use a stylesheet and XSLT
    As it says in your output:
    - <!--
    | Uncomment the following processing instruction and replace
    | the stylesheet name to transform output of your XSQL Page using XSLT
    <?xml-stylesheet type="text/xsl" href="YourStylesheet.xsl" ?>
    -->
    A nice tutorial on XSLT is available on the XML technology center in OTN:
    See Transforming XML with XSLT
    http://otn.oracle.com/tech/xml/learner.html

  • 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 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 .dat file and its contents?

    Hi There
    Can anybody let me know the procedure of how to create new .ctl or .dat file to load data to tables.
    i working on 2day dba chapter 8. it shows me how to creat table and use .dat file to load data. but doesnot giv any clue how new .dat file and its contents can be created. please help.
    thanks in advance.

    Thanks for ur help
    I ve created txt file in notepad and saved it as dat file. tried to load that data thru Enterprise manager. used load data from User files everything went well and job was showing suceeded but dont know why that data is not showing in the table. i ve tried it now for three four times. used right table and pathe but dont know. has anybody got idea why that ll be?
    Thanks

  • How to Save a XML file using Document Object

    Hai all,
    I am new to XML and i created a application to insert a node in the XML file using org.w3c.dom.Document object. And want to know which method has to be used to store the Document object into a XML fille.

    The standard way would be to use a transformer with no transformation where the destination is a StreamResult.
    something like:
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(new DOMSource(doc), new StreamResult("output.xml"));

Maybe you are looking for

  • Customer Classification..table update AUSP

    Hi Guru's I have to update the customer classification via table AUSP Table AUSP is only table which stores the Information Characterstics Values maintained for a Class type. I am updating this table directly via Z program. data : it type STANDARD TA

  • Deployment failed: No managed servers to service request: how to recover

    I am unable to deploy applications, instead get error: 2013-05-14 05:27:53 CDT: Starting action "Deploy Application" 2013-05-14 05:27:53 CDT: Deploy Application started 2013-05-14 05:27:53 CDT: Deployment failed: No managed servers to service request

  • How to print out the RFQ

    Hi all, i want printout of the RFQ. What i have to do for that? thanks

  • Internet Browsers always Rainbow Spiral thinking mode

    On all the browsers I have used: Safari, Firefox, Chrome Every now and then my browser immediately gets the Rainbow Spiral "thinking mode" and I can't do anything on my browser until it stops thinking. (Some times its thinking for 10 minutes until I

  • Broken Table - Debug Info

    Hi All When I edit a page the tables are breaking, I think its becuas eof the debug info and scope variables being displayed as well. I have turned debug info off in CF admin but it still continues. Any ideas why? Many Thanks