dom doc to string

时间:2009-10-14 14:35:02

标签: java dom

我在java中有一个方法,它有2个String参数,并且它将字符串写入文件,现在我有dom doc,它包含我需要写入文件但不是字符串类型的值,如何将其转换为这里的字符串是我的代码:

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);
    }
  }
}

2 个答案:

答案 0 :(得分:1)

为什么要将其转换为String?只是稍后将其写入文件?为什么不做呢

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

如果您需要字符串:

StringWriter w = new StringWriter();
Result dest = new StreamResult(w);
tFormer.transform(source, dest);
String xmlString = w.toString();

答案 1 :(得分:1)

这是解决方案:

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);
    }
  }
}