Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa XML java test

Have Programming Question? Ask it here!
 
 
 


Janardhan yadav
java test
2 Answer(s)      3 years and 2 months ago
Posted in : XML


How to read the data from an .csv file and write into an xml file using java? (test_sample.csv(it should contain at least 39 lines)) i tried this plz check it.

package Test2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXMLFile {

 public static void main(String argv[]) throws IOException  {

    try{
        FileReader fr=  new FileReader("C:\\Documents and Settings/janardhany/Desktop/test_sample.txt") ; 
        BufferedReader br = new BufferedReader(fr);
    //  FileInputStream fStream = new FileInputStream("C:\\Documents and Settings/janardhany/Desktop/test_sample.xls");
     // DataInputStream br= new DataInputStream(fStream);
        String s=null; 
        String s2=null;

//      while((s=br.readLine())!=null ){
//          String in = br.readLine();
//            String f[] = in.split(",");
//           // StringTokenizer st = new StringTokenizer(s, "\t"); 
//          // while(st.hasMoreTokens()) { 
//      
//              // System.out.println( st.nextToken()); 
//        //   }
//            
//            }
//      
//  //  s2=st.nextToken();

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();


      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("ProductCatalogue");
      doc.appendChild(rootElement);

      while((s=br.readLine())!=null ){
            String in = br.readLine();
              String f[] = in.split(",");
      for(String i : f)
      {


for(int i1=0;i1<39;i1++)    
{
      Element pi = doc.createElement("Product_info");
      rootElement.appendChild(pi);



      Element skn = doc.createElement("Skn");
      skn.appendChild(doc.createTextNode(i));
      pi.appendChild(skn);


      Element upc = doc.createElement("UPC");
      upc.appendChild(doc.createTextNode("mook kim"));
      pi.appendChild(upc);


      Element pid = doc.createElement("Product-Id");
      pid.appendChild(doc.createTextNode("mkyong"));
      pi.appendChild(pid);


      Element con = doc.createElement("Content");
      con.appendChild(doc.createTextNode("100000"));
      pi.appendChild(con);



      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result =  new StreamResult(new File("C:\\Documents and Settings/janardhany/Desktop/testing1.xml"));
      transformer.transform(source, result);
}}}
      System.out.println("Done");

     }catch(ParserConfigurationException pce){
      pce.printStackTrace();
     }catch(TransformerException tfe){
     tfe.printStackTrace();
     }
 } 
}

Plz send me code..


Advertisement
View Answers

June 17, 2011 at 3:29 PM


Try this:

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import jxl.Cell; 
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings; 
import jxl.read.biff.BiffException;

class StoreCSVDataToXML{

       public static void main(String[] args)throws Exception {
       ArrayList<String> list1=new ArrayList<String>();
       ArrayList<String> list2=new ArrayList<String>();
       ArrayList<String> list3=new ArrayList<String>();

     WorkbookSettings ws = null;
    Workbook workbook = null;
    Sheet s = null;
    Cell rowData[] = null;
    int rowCount = 0;
    int columnCount = 0;
    int totalSheet = 0;

        ws = new WorkbookSettings();
        ws.setLocale(new Locale("en", "EN"));
        workbook = Workbook.getWorkbook(new File("C:/data.csv"), ws);

        s = workbook.getSheet(0);
        rowCount = s.getRows();
        columnCount = s.getColumns();
        for(int i = 1; i < rowCount; i++){
            rowData = s.getRow(i);
            if(rowData[0].getContents().length() != 0){ 
                for(int j = 0; j < columnCount ;j++){
                 switch(j){
                    case 0:
                        System.out.println("ID: "+rowData[j].getContents());
                        list1.add(rowData[j].getContents());
                        break;
                    case 1:
                        System.out.println("Name: "+rowData[j].getContents());
                        list2.add(rowData[j].getContents());
                        break;
                    case 2:
                        System.out.println("Address: "+rowData[j].getContents());
                        list3.add(rowData[j].getContents());
                           break;
                       }
                     }
                  }
        }
    workbook.close();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder();
    Document doc = documentBuilder.newDocument();

        Element root = doc.createElement("Employee");
        doc.appendChild(root);

        for(int i=0;i<list1.size();i++){

        Element child = doc.createElement("Id");
        root.appendChild(child);

        Text text = doc.createTextNode(list1.get(i).toString());
        child.appendChild(text);

        Element child1 = doc.createElement("Name");
        root.appendChild(child1);

        Text text1 = doc.createTextNode(list2.get(i).toString());
        child1.appendChild(text1);

        Element child2 = doc.createElement("Address");
        root.appendChild(child2);

        Text text2 = doc.createTextNode(list3.get(i).toString());
        child2.appendChild(text2);
        }
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File("c:/new.xml");
        FileWriter fw=new FileWriter(file,true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(xmlString);
        bw.flush();
        bw.close();

      System.out.println("Xml File is Created Successfully");
  }
}


June 17, 2011 at 3:32 PM


For the above code, you need to download jxl.jar and put it into Java lib.



Related Tutorials/Questions & Answers:
java test
java test  How to read the data from an .csv file and write into an xml file using java? (test_sample.csv(it should contain at least 39 lines)) i...:\\Documents and Settings/janardhany/Desktop/test_sample.txt
how to conduct the test in java
how to conduct the test in java  how to conduct the test in java
Advertisements
java test - Java Beginners
java test   Trace through the following program segment and state clearly the output that will be generated: public static void main(String [] args){ int no1; int no2; for (no1 = -2; no1 <= 1; no1++){ for (no2
Java: Example - Palindrome test
Java: Example - Palindrome test //========================================================= isPalindrome // This method returns 'true' if the parameter // is a palindrome, a word that is spelled the // same both
online test application in java
Online Test Application Table Of Contents Introduction To Application Database Design Creating Data Access Object (DAO) Design Pattern Creating Views Writing Actions Mapping Application Admin Module User Module Download
Create test engine - Java Beginners
Create test engine  How can create a test engine dat generates questions randomly using javax.swing in java
online test application in java
online test application in java  Can questions come in html file (test.html) if we link test.jsp with test.html   We have taken radiobuttons in our application, you can take textarea, textfield etc. Here we have created
Java File Handling Test Results
Java File Handling Test Results   Is somebody able to help me with this Write a program to read each name from the file and prompt the user... java.io.*; public class Test { public static void main(String[] args) throws
junit test case - Java Beginners
junit test case  how to use junit for testing email id format  Hi Friend, Please visit the following link: http://www.roseindia.net/junit/ Hope that it will be helpful for you. Thanks
online test project on java using servlets and jsp
online test project on java using servlets and jsp  as i am doing online test project on java using jsp and servlets ,,,the problem is in the code...;Here is a jsp application. Here we have created a table test
code for timer in java netbeans for online test series countdown timer
code for timer in java netbeans for online test series countdown timer  code for timer in java netbeans for online test series countdown timer
How to bookmark and preview last question in a java test engine - Java Beginners
How to bookmark and preview last question in a java test engine  Am creating a test engine with java, how can i generate questions randomly, allow a user bookmark a question view previous question and review questions
How to bookmark and preview last question in a java test engine - Java Beginners
How to bookmark and preview last question in a java test engine  Am creating a test engine with java, how can i generate questions randomly, allow a user bookmark a question view previous question and review questions
test case
test case  Hi Can you explain me how to write test case in java. regards kennedy
WRITE AND TEST
WRITE AND TEST   WRITE AND TEST PROGRAM TO ACCEPT A STRING? 1).WHICH STARTS WITH 'S' OR 's' 2).ENDS WITH "nd" 3) THE LENGTH OF THE STRING SHOULD BE 10 OR LESS
Online test
Online test   I am creating a project for online test system. There should be a timer,on pressing next button it will retrieve a next question and it will show on the same page,on completion of test it will show result
CODING TEST
/class structure ΓΆβ?¬ΒΆ Choice of data structures ΓΆβ?¬ΒΆ Unit Test cases ΓΆβ?¬Β
CODING TEST
/class structure ΓΆβ?¬ΒΆ Choice of data structures ΓΆβ?¬ΒΆ Unit Test cases ΓΆβ?¬Β
putting words to line number form a java file/test file and show occurrence
putting words to line number form a java file/test file and show occurrence  hi all i want putting words to line number form a java file and show... and BinarySearchTree and please help me in java coding
online test project
online test project  i need online test project in java using struts...kindly help..   Have a look at the following link: http://www.roseindia.net/struts/struts/struts2.2.1/onlinetestapp
Query to Test MySQL Performance
Query to Test MySQL Performance  Query to Test MySQL Performance
unit test in php - PHP
unit test in php  How can i run the unit test in PHP
Junit @Test annotation
Junit @Test annotation  What is the Application of @Test Annotation in JUnit ?   The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case : public class Example
optional parameter of Test annotattion
optional parameter of Test annotattion   What are two optional parameters of @Test annotation ?   The Test annotation supports two optional parameters. The first, expected, declares that a test method should throw
test case - JUNIT
test case  Hi i am doing project on online reservation i want to know how to write the test case template for this online reservation
optional parameter of Test annotattion
optional parameter of Test annotattion   The Test annotation supports two optional parameters. The first, expected, declares that a test method... a different exception than the one declared, the test fails. For example, the following
Junit Test Suite
Junit Test Suite  Hi Sir I am a beginner to JUnit. I have created these three test classes - CounterTest,MyClassTest & PetTest. I want to run these all with a Test Suite. Please mention code with your answer. Best regards
EclipsePro Test
EclipsePro Test       EclipsePro Test contains the powerful JUnit test generation... Eclipse development environment. JUnit Test Generation & Editing
test cases problem
test cases problem  what to write in the testing phase of my project. My project is a JSP project that generate graphs from the student marks... 6.7.1..please help me with the test cases that could be made out
TEST JAMES MAIL SERVER
TEST JAMES MAIL SERVER  How to test Apache James Mail Server for stress? Which Load Generator should we use to create requests in the form of mail at a controlled rate for SMTP and POP3? Actually I needed to test JVM of the mail
Online Test System Project
Online Test System Project  I want a full ready-made project on online test system in jsp. i am not using servlet but only jsp.And backend database as mysql. my email address is help me. send a full project on online test system
online test system
online test system  Hi, I am creating a project for online test system.There should be a timer,on pressing next button it will retrieve a next question and it will show on the same page,on completion of test it will show
Online Test System Project
Online Test System Project  I want a full ready-made project on online test system in jsp. i am not using servlet but only jsp.And backend database as mysql.   Please visit the following links: http
Build and Test tools
tools available in Java: Java build and Test Tools DBUNIT ANT...Build and Test tools Application Build and Test tools tutorials. In this section are providing tutorials and examples for all the build and test tools
Developing a program to test
Developing a program to test       Developing a program to test Given below program is to test the script : Qunit.html <
Test Actions
Test Actions An example of Testing a struts Action is given below using the junit. In this example the execute method is being test. HelloAction.java... method stub result = helloAction.execute(); super.setUp(); } @Test
contructors 1&test
the 'XXX' with the value of length using the Java keyword this in your code. β??h... to replace the 'XXX' with the values of length and width using the Java keyword... of length, width and height using the Java keyword this in your code. When you
Using JMeter for a Simple Test
Using JMeter for a Simple Test       Lets see how to run JMeter now. We will conduct a simple test to set up a test plan and stress test a Web application. Before proceeding
HttpUnit Test
HttpUnit Test       This example illustrates about how to write a Black Box test using HttpUnit. The Block Box test is useful in evaluating the overall health
Grouping Of Test cases by using struts
Grouping Of Test cases by using struts  Hi, I can able to create, save, delete and execute test cases in my application. But i want to group those test cases. Give me the flow for coding
DbUnit test Life Cycle
DbUnit test Life Cycle     ...;Loading some data from XML file into the database.  Running the test... the test. These steps allow you not to waste time in writing code to restore state
Test and debug enterprise components
and Java classes. To use the Universal Test... Test and debug enterprise components Prev Chapter 1. Design, build and test reusable enterprise
Design, develop and test JSPs
Design, develop and test JSPs Prev Chapter 2. Design, build and test web components Next    Design, develop and test JSPs Creating
Test hidden element using JQuery
Test hidden element using JQuery  Suppose i have an element which i am hiding and showing, using .hide(), .show() or .toggle().How do you test to see if that element is currently hidden or visible on the screen? Please provide
JUnit and Test-Driven Development
Java NotesJUnit and Test-Driven Development Test-Driven Development One... test frameworks make use of Java 5 annotations. The JUnit authors have not been... shift, is Test Driven Development (TDD). This puts writing tests near the front
Running the Test Plan
Running the Test Plan       To run the test plan you can go to Run menu -> Run or press ctrl + r. To indicate that the test is running a green square lits up in the upper-right
Using the QUnit to test jQuery application
Using the QUnit to test jQuery application       Using the QUnit to test jQuery...; $(document).ready(function(){ test("a basic test example"
online test software using jsp and servlet
online test software using jsp and servlet  online test software using jsp and servlet
Struts Test case for File Upload - Struts
Struts Test case for File Upload  I need to write a struts test case for uploading a file of type FileUploadForm setUploadFile(FormFile File){ this.uploaded_file = uploaded_file; } in my test case i need
 

 

 

DMCA.com