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



Home Answers Viewqa WebSevices how to read values from java in xml?
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


divya
how to read values from java in xml?
1 Answer(s)      3 years and 7 months ago
Posted in : WebSevices


how to read values from java in xml?


Advertisement
View Answers

March 5, 2011 at 10:48 AM


Java read values from console and stored it into xml file

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

public class CreatXMLFile {
  public static void main(String[] args) throws Exception {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter number to add elements in your XML file: ");
    String str = bf.readLine();
    int no = Integer.parseInt(str);
    System.out.print("Enter root: ");
    String root = bf.readLine();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElement(root);
    document.appendChild(rootElement);
    for (int i = 1; i <= no; i++){
      System.out.print("Enter the element: ");
      String element = bf.readLine();
      System.out.print("Enter the data: ");
      String data = bf.readLine();
      Element em = document.createElement(element);
      em.appendChild(document.createTextNode(data));
      rootElement.appendChild(em);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result =  new StreamResult(new File("C:/file.xml"));
        transformer.transform(source, result);
  }
}


Related Tutorials/Questions & Answers:
Advertisements
Advertisements
 

 

 

DMCA.com