1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

To convert between XML and DOM in Java

Last updated at Posted at 2015-01-21

DOM3 にては Load & Save 機能 有りて package org.w3c.dom.ls に これら 有り。

import org.w3c.dom.ls.*;

DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS ls = (DOMImplementationLS) registry.getDOMImplementation("LS 3.0");

やゝ 詳しく 書くに

DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementation dom = registry.getDOMImplementation("+LS 3.0 +XPath 3.0");
DOMImplementationLS ls = (DOMImplementationLS) dom.getFeature("+LS", "3.0");

して
load すなはち XML → DOM は

LSInput lsInput = ls.createLSInput();
FileInputStream fis = new FileInputStream(path);
lsInput.setByteStream(fis);
lsInput.setEncoding("UTF-8");

LSParser lsParser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
Document document = lsParser.parse(lsInput);

save すなはち DOM → XML は

LSOutput lsOutput = ls.createLSOutput();
FileOutputStream fos = new FileOutputStream(path);
lsOutput.setByteStream(fos);
lsOutput.setEncoding("UTF-8");

LSSerializer lsSerializer = ls.createLSSerializer();
serializer.write(document, lsOutput);

LSSerializer は 次の 如く 飾り 得:

serializer.getDomConfig().setParameter("comments", false);
serializer.getDomConfig().setParameter("format-pretty-print", true);
serializer.getDomConfig().setParameter("xml-declaration", false);
...

ちなみに それ以前にては 次の ごとく しき。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setnamespaceAware(false);
factory.setValidating(false);
factory.setExpandEntityRefereces(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOUtputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(outputStream);
transformer.transform(source, result);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?