細かい説明は後で。
今日は眠いから取りあえずアップ。
こんなXMLを作りたい。
<root> <devil> <misician no="0">小暮伝衛門</misician> <album no="0">好色萬声男</album> </devil> <devil> <misician no="1">CANTA</misician> <album no="1">流星と春の嵐</album> </devil> </root>
package com.fudebaco.util; import com.fudebaco.bean.SampleXmlBean; import java.util.ArrayList; import java.util.List; 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; public class XmlSample { public static void main(String args[]){ List<SampleXmlBean> list = createSampleList(); try { DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = dbfactory.newDocumentBuilder(); Document document = docbuilder.newDocument(); // ノード生成 Element root = document.createElement("root"); // ノードをDocumentに追加 document.appendChild(root); for (int i = 0; i < list.size(); i++) { SampleXmlBean bean = list.get(i); Element sep = document.createElement("devil"); root.appendChild(sep); Element elem1 = document.createElement("misician"); elem1.setTextContent(bean.getElem1()); elem1.setAttribute("no", Integer.toString(i)); sep.appendChild(elem1); Element elem2 = document.createElement("album"); elem2.setTextContent(bean.getElem2()); elem2.setAttribute("no", Integer.toString(i)); sep.appendChild(elem2); } /* * DOMオブジェクトを文字列として出力 */ TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.setOutputProperty("method", "html"); // 宣言を出さない transformer.transform(new DOMSource(document), new StreamResult(System.out)); } catch (Exception e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } private static List<SampleXmlBean> createSampleList() { List<SampleXmlBean> list = new ArrayList<>(); SampleXmlBean bean1 = new SampleXmlBean(); bean1.setElem1("小暮伝衛門"); bean1.setElem2("好色萬声男"); list.add(bean1); SampleXmlBean bean2 = new SampleXmlBean(); bean2.setElem1("CANTA"); bean2.setElem2("流星と春の嵐"); list.add(bean2); return list; } }