How to Generate XML File from Java Code.

I want to generate the xml file from the java code.
Could you plz suggest any webSite address with example?

Here is the code
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
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.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXML {
     private DocumentBuilderFactory factory = null;
     private DocumentBuilder builder = null;
     private Document document = null;
     public CreateXML() {
          try {
               factory = DocumentBuilderFactory.newInstance();
               builder = factory.newDocumentBuilder();
               document = builder.newDocument();
          } catch (FactoryConfigurationError e) {
               e.printStackTrace();
          } catch (ParserConfigurationException e) {
               e.printStackTrace();
     /** Creates the document for xml. */
     public Document createDocument(){
          try{               
               Element root = document.createElement("Root");
               Element child = document.createElement("child");
               root.appendChild(child);
               document.appendChild(root);
          }catch(RuntimeException e){
               e.printStackTrace();
          return document;
     /** Saves the document as xml. */
     public void saveDocument(Document document){
          try{
               TransformerFactory transFactory = TransformerFactory.newInstance();
               Transformer transformer = transFactory.newTransformer();
               DOMSource source = new DOMSource(document);
               StreamResult stream = new StreamResult(new File("sample.xml"));
               transformer.transform(source, stream);
               System.out.println("XML Created !!");
          }catch(TransformerConfigurationException e){
               e.printStackTrace();
          } catch (TransformerException e) {
               e.printStackTrace();
     public static void main(String args[]){
          CreateXML createXML = new CreateXML();
          Document document = createXML.createDocument();
          createXML.saveDocument(document);
}

Similar Messages

  • How to Read and Generate XML file from java code.

    hi guys,
    how to read the xml file (Condition :we know only DTD or Shema only).
    How to Generate the new xml file ?(using Shema )
    And one more how directly Generate the xml from DB?
    Pleas with code or any URL

    Using XMLbeans you can generate Java objects from an XSD schema (perhaps DTDs aswell)
    Then you can create an instance of the Document object and ask it to write itself.
    This will create an XML document complient to the schema.
    XMLBeans generates a "type" safe DOM where you can only ever have a structure compilent to you schema.
    matfud

  • How to modify an existing xml file from java code.

    Hi
    I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
    For example if xml file(studlist.xml) is as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    Now suppose i have set name to victor using student.setName,
    and set age to 20 using setAge from javacode,
    the new xml file is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    <Student>
              <Name>victor</Name>
              <Age>20</Age>
         </Student>
    As observed this is not a valid xml file.But how can i modify without any errors?

    I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
    Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
    What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
    // gets the root element of the specified file (code not shown)
    Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
    // write a new student element
    Element student = document.createElement("Student");  // creates the new student
    rootElement.appendChild(student); // ***appends it to the root element***
    Element name = document.createElement("Name"); // creates the name element
    name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
    student.appendChild(name); // appends the name to the student
    Element age= document.createElement("Age"); // creates the age element
    age.appendChild(document.createTextNode("26")); // adds the age text to the age element
    student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
    Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM

  • Generation of xml file from java code

    hi,
    I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?

    Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

  • How to generate XML file from SQL file !

    I am new to XML publisher. I known one way to generate XML file is register one report file in concurrent manager.
    But I want to generate XML file from sql file.
    Could someone show me how to code in sql file, how to register is in concurrent manager.
    Thanks !

    Hi
    Phew ... not sure we have the space here. So I can point you in the right direction:
    1. XML data generation - there are two packages in the db you can use with a plsql procedure, XMLGEN and SQL XML. You can also use java APIs too. Try checking the db documentation and search for the above methods.
    2. Registering the report - the system administrators guide will provide this info. Hooking the program up with XMLP is covered here - http://www.oracle.com/technology/products/applications/publishing/resource/CM%20Whitepaper5.0.pdf
    Regards, Tim

  • How to read XML files from java

    i need a sugession that how to read a xml file using java code
    and i need to parse using some parsers and display attributes and entity seperately
    as a string.......

    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.io.SAXReader;
    import java.io.File;
    import java.text.AttributedCharacterIterator.Attribute;
    import java.util.Iterator;
    import java.util.StringTokenizer;
    public class XmlParser
    private String Result="";
    private String Final="";
    private String Delim="";
    public void bar1(Document document) throws DocumentException
    org.dom4j.Element root = document.getRootElement();
    // System.out.println(root.getName());
    bar2(root);
    System.out.println(this.Result);
    process();
    public void bar2(org.dom4j.Element e)
    for(Iterator i = e.elementIterator();i.hasNext();)
    org.dom4j.Element Element = (org.dom4j.Element) i.next();
    Result += Element.getName()+"\t"+Element.getText()+"\n";
    bar2(Element);
    public void process()
    StringTokenizer Tokenizer = new StringTokenizer(this.Result,"\n");
    String element;
    while(Tokenizer.hasMoreTokens())
    element = Tokenizer.nextToken();
    StringTokenizer Tokenizer2 = new StringTokenizer(element,"\t");
    // Do what ever String Process here Example
    this.Final += element.getName();
    this.Final += this.Delim;
    System.out.println(this.Final);
    public static void main(String s[])throws Exception
    Document document = null;
    SAXReader reader = new SAXReader();
    File f1= new File("D:/Rajesh/EDI to XML/EDI.xml");
    document = reader.read(f1);
    Demo obj = new Demo();
    obj.bar1(document);
    i think this will hep full.......

  • Best Practices:: How to generate XML file from a ResultSet

    Hi all,
    Could someone please suggest the best practices of how to generate an XML file from a resultset? I am developing a web application in Java with Oracle database and one of my tasks is to generate an XML file when the user, for example, click a "download as XML" button on the JSP. The application is basically like an Order with line items. I am using Struts and my first thought has been to have an action class which will extend struts's DownloadAction and through StAX's Iterator API to create an XML file. I intend to have a POJO which will have properties of all columns of my order and line items tables so that for each order I get all line items and:
    1. Write order details then
    2. Through an iterator write line items of that order to an XML file.
    I will greatly appreciate for comments or suggestions on the best way to do this through any pointers on the Web.
    alex

    Use a OracleWebRowSet in which an XML representation of the result set may be obtained.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/oracle10g/webrowset/Readme.html
    http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/jcrowset.htm

  • How to copy a file from Java code

    I have written a file through Java code in folder, say, "A". Now, I want a copy of that file exactly the same in some other folder "B". How, it can be done?

    http://java.sun.com/docs/books/tutorial/essential/io/streams.html

  • Reference faces-config.xml file from java code.

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

  • How to generate XML file from oracle database query result

    Hi dudes,
    as stated on the subject, can anyone suggests me how can i achieve the task stated above??
    Here is a brief description of my problem:
    I need to create a XML file once i query from the oracle database, and the query result returned from the database will be stored in XML file.
    I'd searched around the JAXB, DOM, SAXP and the like basic concepts, but i still don't know how to start??
    Any suggestions ???

    Read this:
    http://www.cafeconleche.org/books/xmljava/chapters/ch08s05.html
    You might have to read more of the book to understand that chapter.

  • How to generate xml file from an array of data using jQuery

    Hi All,
    Iam facing the problem with diaplaying array of data into a xml file, Actually iam using SAPUI5 commons table to display the backend data, each row in the table has checkbox. If we select each checkbox, iam getting the particular record and push it into an empty array and then i should show that array of data into xml file.

    OData.request 
    requestUri: url,  
    method: "POST",
    headers: {                    
    "X-Requested-With": "XMLHttpRequest",                  
    "Content-Type": "application/atom+xml",
    "DataServiceVersion": "2.0", 
    "Accept": "application/atom+xml,application/atomsvc+xml,application/xml",  
    "X-CSRF-Token": header_xcsrf_token   
    data: requestTableDATAArray
    // Response after posting and set message
    function (data, response) 
    alert(response.body);//gives xml format

  • Generate XML File from table

    How to generate XML file from a table without using UTL_FILE that too in local machine...

    You downloaded the wrong XML Parser!
    XSQL requires Java Parser. Well, there's a copy included with the XSQL package so you actually don't need to do another download.
    You really don't need XSQL if you just want a XML file from DB, you just needed a XML SQL Utility. Download that and run the samples.

  • Hi I need this asap... "Java code to generate XML File from XML Schema"

    Hi all....
    I need this asap... "Java code to generate XML File from XML Schema i.e XML Schema Definition, XSD file".
    Thankz in advance...
    PS: I already posted in the afternoon... this is the second posting.

    take look at :
    http://sourceforge.net/projects/jaxme/
    this might help...

  • Java code to generate XML File from XML Schema

    Hi I need this asap... "Java code to generate XML File from XML Schema i.e XML Schema Definition, XSD file".
    Thankz in advance...

    JAXB has been available as an early release download for some time. There are also XML Binding packages available from Borland (JBuilder) and Castor. These tools create Java classes from a source document, xml,dtd etc. You can use these classes to marshal-unmarshal XML documents.
    Dave

  • How to edit the existing data in the XML file from java programming.

    Hi all
    i am able to create XML file with the sample data as below from java programming.
    i need sample code on how to edit the existing data in the XML file?
    for example
    <?xml version="1.0"?>
       <mydata>
               <data1>
                         <key1>467</key1>
                        <name1>Paul</name1>
                        <id1>123</id1>
              </data1>
              <data2>
                         <key2>467</key2>
                        <name2>Paul</name2>
                        <id2>123</id2>
              </data2>
        </mydata>
    i am able to insert the data in the XML.
    now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
    Regards
    Sunil
    [points will be always rewardable]

    hi
    u need a parser or validate the xml file for to read the xml file from java coding u need for this
    xml4j.jar u can download this file  from here
    http://www.alphaworks.ibm.com/tech/xml4j
    or we can use the SAX(simple API for XML)
    some sample applications for this
    http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
    http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
    http://www.xml-training-guide.com/e-xml44.html
    let me know u need any other info
    bvr

Maybe you are looking for

  • Acrobat 9 print problem

    I recently upgraded my Mac Pro from Tiger and Acrobat 8 Pro to Leopard and Acrobat 9 Pro (I know, I'm a little late to the upgrade party - apologies but it's hard to find free time to keep up with the software maintenance; Acrobat X and Snow Leopard

  • Zen 4 - Zen 6.5 Inventory database upgrade fails

    Hi all, Have installed Zen 6.5 over a Zen 4 server (nw65) running inventory. Database is on a seperate oracle server. When I start inventory, it starts the database upgrade and then fails with a java exception part way through, and then says "stoppin

  • Schedule 3 reports to one xls fil????e

    hi all..... using ibots i have scheduled 3 reports which are present on my dashboard. i want all these 3 reports to be saved as .xls under 3 sections but under a common excel file.. how can this be achieved??? regards mahi Edited by: Mahis on Dec 27,

  • Apps are running only in Terminal

    Hello everybody. I have some games , they don't start when I click on the Icon. It jumps in dock but after a minute ist stops and stuck. When I go to Package Content and start the App from the MAC OS folder in terminal it works. Can anybody tell me a

  • What is the default package tu put in a data model ?

    Hi, I want to call a procedure *"EXTRACTION"* which is located in the default pachkage of my database. What shoud i put in my data model? i feel that this line is wrong : *<dataTrigger name="beforeReport" source="Extraction"/>* Thnaks, SAAD