1

我正在使用以下代码从 xml 文件中删除一些特定节点..它在控制台上显示正确的输出,但不知何故 xml 文件没有得到更新..内容保持原样..请帮助..谢谢...

package com.sumit.xml.client;

import java.io.*;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
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 ReadCDATA {
  static public void main(String[] arg) {
  try{
  BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter a XML file name: ");
  String xmlFile = bf.readLine();
  File file = new File(xmlFile);
  System.out.print("Enter an element which have to delete: ");
  String remElement = bf.readLine();
  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();

  }
  else{
  System.out.println("File not found!");
  }
  }
  catch (Exception e){
  System.err.println(e);
  System.exit(0);
  }
  }
} 
4

4 回答 4

2

DOM 仅在进程内存中更改。您显示的代码中没有任何内容可以透明地将数据写入基础 XML 文件。

你需要添加类似的东西

createOutputFile("output.xml", transformToString(document));

private static String transformToString(Document document) {
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(document), new StreamResult(buffer));
        return buffer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}


private static void createOutputFile(String filePath, String content) {
    FileWriter writer = null;
    try {
        try {
            writer = new FileWriter(filePath);
            writer.write(content);
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close(); 
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
于 2012-05-04T10:17:01.650 回答
0

您还应该在文件的 OutputStream 上调用 TFormer.transform

于 2012-05-04T10:14:14.060 回答
0

从 xml 中删除节点后,将内容写入 xml 文件

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));

  Document doc = db.parse(is);


// write the content into xml file

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(filepath));
    transformer.transform(source, result);

将内容写入 xml 文件后,xml 文件将得到更新。

于 2015-06-27T06:19:06.223 回答
0
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        String filepath = "/java/CarsNEW.xml"; //according to yuor path and file name
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);
于 2017-03-03T09:53:49.560 回答