top / index / prev / next / target / source

2015-07-14 diary: Java で XML 読み書き

いがぴょんの日記 日記形式でつづる いがぴょんコラム ウェブページです。

Java で XML 読み書き

よく忘れてしまいます。今一度、メモ。

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Sample {

  public static void main(String[] args) throws Exception {
    Element rootElement = null;
    {
      // read xml
      final DocumentBuilder builder = DocumentBuilderFactory
          .newInstance().newDocumentBuilder();
      final Document document = builder.parse(new File("./build.xml"));
      rootElement = document.getDocumentElement();
    }

    final NodeList nodeList = rootElement.getChildNodes();
    for (int index = 0; index < nodeList.getLength(); index++) {
      final Node look = nodeList.item(index);
      System.out.println(look.toString());
    }

    {
      // write xml
      final Transformer transformer = TransformerFactory.newInstance()
          .newTransformer();
      final DOMSource source = new DOMSource(rootElement);
      final OutputStream outStream = new BufferedOutputStream(
          new FileOutputStream(new File("./build-test.xml")));
      final StreamResult target = new StreamResult(outStream);
      transformer.transform(source, target);
    }
  }
}

この日記について