Solved

Writing to xml with java

Posted on 2003-11-22
3
300 Views
Last Modified: 2010-03-31
I have a java application that reads from an xml file, parses the file, updates the values stored in the tree but i don't know how to save the changes to the XML file. I've included the code below. I know it's a bit distorted but maybe you might be able follow it. I do't think you need to see the xml file but i can include it if it will help. In the class writeTree i've began writing to the xml file. Do i have to write each node and child to the xml file seperately or is there an easier way. Any help would be much appreciated, Thanks

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;
import java.io.*;
import java.text.*;

public class Parse{
     public static void main(String args[]){
          File docFile = new File("students.xml");
          Document doc = null;
          try{
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               DocumentBuilder db = dbf.newDocumentBuilder();
               doc = db.parse(docFile);
          }catch(Exception e){
               System.out.println("error parsing file");
          }
          Element root = doc.getDocumentElement();
          System.out.println("Root: "+root.getNodeName());
         
          transverseDomTree(root);          
          //getSubjects(root);
          //getResult(root);
          //createElement(root, doc);
          //writeTree(doc);
     }
     
     public static void transverseDomTree(Node start){
          Node child;
          System.out.println(start.getNodeName()+"="+
          start.getNodeValue());
          for(child = start.getFirstChild();child!=null;child=
               child.getNextSibling()){
               transverseDomTree(child);
          }
     }
     
     public static void getSubjects(Element start){
          NodeList subjects = start.getElementsByTagName("subject");
          for (int i = 0;i < subjects.getLength();i++){
               
               NamedNodeMap atts = subjects.item(i).getAttributes();
               System.out.println(atts.item(0).getNodeValue());
               //System.out.println(subjects.item(i).getChildNodes().item(1).getFirstChild().getNodeValue());          
          }
     }
     
     public static void getResult(Element start){
          System.out.println("Enter subject name: ");
          String input = new String();
          BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
          try{
               input = console.readLine();
               NodeList subjects = start.getElementsByTagName("subject");
                    for (int i = 0;i < subjects.getLength();i++){
                    NamedNodeMap atts = subjects.item(i).getAttributes();
                    if(input.equals(atts.item(0).getNodeValue())){
                         float result = Float.parseFloat(subjects.item(i).getChildNodes().item(1).getFirstChild().getNodeValue());
                         System.out.println("Subject: "+atts.item(0).getNodeValue()+
                                                "Result: "+result);
                    }    
          }
          }catch (IOException e) {
            System.out.println("name = < "+ e + ">");
        }
         
     }
     
     public static void createElement(Element start, Document doc){
          Element subjectNode = doc.createElement("subject");
          Element resultNode = doc.createElement("result");
          subjectNode.setAttribute("name","Java Programming");
          resultNode.appendChild(doc.createTextNode("60.00"));
          subjectNode.appendChild(resultNode);
          start.insertBefore(subjectNode,start.getLastChild());
     }
     
     public static void removeChild(Element start){
          System.out.println("Enter subject to be deleted: ");
          String input = new String();
          BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
          try{
               input = console.readLine();
               NodeList subjects = start.getElementsByTagName("subject");
                    for (int i = 0;i < subjects.getLength();i++){
                    NamedNodeMap atts = subjects.item(i).getAttributes();
                    if(input.equals(atts.item(0).getNodeValue())){
                              Element deleted=null;
                              deleted.removeChild(atts.item(0));
                    }    
          }
          }catch (IOException e) {
            System.out.println("name = < "+ e + ">");
        }
     }
     
     public static void writeTree(Document doc){
          try{
               File newFile = new File("students.xml");
               FileWriter newFileStream = new FileWriter(newFile);
               newFileStream.write("<?xml version=\"1.0\"?>\n");
               newFileStream.close();
          }catch (IOException e) {
            System.out.println("name = < "+ e + ">");
        }
     }
}
0
Comment
Question by:liamgannon
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 9802815
0
 

Author Comment

by:liamgannon
ID: 9802870
Great help, thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9802885
:-)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
check java version using powershell 13 293
ejb example issues 3 52
Java 8 to Java 6 8 32
Website checklist for browser compatibility? 2 37
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question