0

以下のコードを使用しています。ただし、コードを実行するたびに、新しい XML を同じ TXT ファイルに上下に追加したいと考えています。JDOMを使用してそれが可能ですか。Plsは私を助けて..

xmlOutput.output(doc, new FileWriter("c:\updated.txt")); 変更する必要があるものですか?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class Replacer {
    public static void main(String[] args) {
          try {

            SAXBuilder builder = new SAXBuilder();
            File xmlFile = new File("c:\\file.xml");
            String temp = "1234567";

            Document doc = (Document) builder.build(xmlFile);
            Element rootNode = doc.getRootElement();

            System.out.println("Root Node is --> "+rootNode);

            Element ShipmentLines = rootNode.getChild("ShipmentLines");

            Element ShipmentLine = ShipmentLines.getChild("ShipmentLine");

            Element Containers = rootNode.getChild("Containers");

            Element Container = Containers.getChild("Container");


            ShipmentLine.getAttribute("OrderNo").setValue(temp);


            Container.getAttribute("ContainerScm").setValue(temp);

            XMLOutputter xmlOutput = new XMLOutputter();

            xmlOutput.setFormat(Format.getPrettyFormat());
            xmlOutput.output(doc, new FileWriter("c:\\updated.txt"));

          } catch (IOException io) {
            io.printStackTrace();
          } catch (JDOMException e) {
            e.printStackTrace();
          }
}
}
4

1 に答える 1

1

JDOM は、既存のファイルへの追加を直接サポートしていませんが、少量の追加コードのみが必要です。出力を StringWriter に書き込み、文字列を取得して、その文字列を既存のファイルに追加するだけです。考えられる実装の 1 つ:

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
StringWriter out = new StringWriter();
xmlOutput.output(doc, out);
FileUtils.writeStringToFile(new File("c:\\updated.txt"), out.toString(), true);

ここでは、commons-io FileUtils クラスを使用してごまかしています。Apache Commons I/O を使用してファイルにデータを追加するを参照 してください。

commons-io がアプリで利用できないか実用的でない場合は、独自の append-string-to-file メソッドを記述します。

于 2012-09-13T19:15:40.187 に答える