tags:

views:

250

answers:

2

I have a method in java that has 2 String parameters and it writes string to a file, now I have dom doc that holds value that I need to write to a file but its not string type, how can I convert it to a string here is my code :

import java.io.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

    public static boolean saveStringToFile(String fileName, String saveString)
    {
     boolean saved = false;
     BufferedWriter bw = null;

     try {
      bw = new BufferedWriter(new FileWriter(fileName));

       try {
        bw.write(saveString);
        saved = true;
       }
       finally {
        bw.close();
       }
     }
     catch(IOException ex)
     {
      ex.printStackTrace();
     }
     return saved;
    }

  static public void main(String[] arg) {
    try{
      String xmlFile = "Management.xml";
      File file = new File(xmlFile);
      String remElement = "Physical_Order_List_Array";
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);
//        Remove the node
        element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(System.out);
        tFormer.transform(source, dest);
       // System.out.println();
       // saveStringToFile("emir.xml", "dsds"); -> write method
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}
A: 

Why do you want to convert it to String? Just to write it to a file later? Why not only do

 Result dest = new StreamResult(new FileOutputStream("foo.xml"));

If you need a String:

StringWriter w = new StringWriter();
Result dest = new StreamResult(w);
tFormer.transform(source, dest);
String xmlString = w.toString();
sfussenegger
Well there is a problem, when this line is present Result dest = new StreamResult(System.out); code is successfuly removing Physical_Order_List_Array element from xml file, but when I try to output it to a file no matter string or directly, the xml file stays unchanged.
c0mrade
I don't have a solution for this question (and no time to test it myself). However, you might try using another file (or renaming the old one first) and see if this works. Additionally, this is most likely what you want to do anyway, as you proabably don't want to leave your user with a partial file after a program crash. (i.e. make sure you wrote your file successfully before changing the old one)
sfussenegger
tried that already .. it doesn't work .. tnx I'll try to figure something although its not easy so late ..
c0mrade
In this case you have a problem with writing files, not with serializing a DOM to string.
sfussenegger
+1  A: 

here is the solution :

import java.io.*;

import org.w3c.dom.*;

import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

     public static void removeAll(Node node, short nodeType, String name) {
            if (node.getNodeType() == nodeType &&
                    (name == null || node.getNodeName().equals(name))) {
                node.getParentNode().removeChild(node);
            } else {

                NodeList list = node.getChildNodes();
                for (int i=0; i<list.getLength(); i++) {
                    removeAll(list.item(i), nodeType, name);
                }
            }
        }

  static public void main(String[] arg) {
    try{
      String xmlFile = "Management.xml";
      File file = new File(xmlFile);
      String remElement = "Physical_Order_List_Array";
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        // Obtain a node
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);


        element.getParentNode().removeChild(element);


        removeAll(doc, Node.ELEMENT_NODE, remElement);

        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(new FileOutputStream("Management.xml"));
        tFormer.transform(source, dest);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}
c0mrade