読者です 読者をやめる 読者になる 読者になる

テストなどで使用するXMLファイルを自動で作成するサンプル

5年程前に作成した「テストなどで使用するXMLファイルを自動で作成するサンプルプログラム」のソースを書いておこうと思います。

どのような構造のデータを作成するかはXMLファイルで指定する事ができます。

 

ソース(XmlTestMain5.java)


package jp.co.hoshisoft.xmltest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class XmlTestMain5 {

    public static void main(String args) {
        XmlTestMain5 test = new XmlTestMain5();
        test.execute("Test5.xml", "result5.xml");
    }
   
    public void execute(String xmlPath1, String xmlPath2) {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) transFactory;
       
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document doc = documentBuilder.parse(new File(xmlPath1));

            TransformerHandler saxHandler = saxTransformerFactory.newTransformerHandler();
            saxHandler.setResult(new StreamResult(new FileOutputStream(xmlPath2)));
            saxHandler.startDocument();
       
            Node root = doc.getFirstChild();
            putNodeStartTag(root, saxHandler);
           
            NodeList nodeList = root.getChildNodes();
            for(int i=0;i<nodeList.getLength();i++) {
                Node node = nodeList.item(i);
                putNode(node, saxHandler, 0);
            }

            putNodeEndTag(root, saxHandler);
           
            saxHandler.endDocument();

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
   
    private void putNode(Node node, TransformerHandler saxHandler, int no) throws SAXException {

        switch(node.getNodeType()) {
            case Node.TEXT_NODE :
                putNodeTextTag(node, saxHandler, no);
                break;
            case Node.ELEMENT_NODE :
                if(node.getNodeName().equals("for")) {
                    NamedNodeMap map = node.getAttributes();
                    String numString     = map.getNamedItem("num").getNodeValue();
                    String tagNameString = map.getNamedItem("tagName").getNodeValue();
                    int num = Integer.parseInt(numString);
                    for(int i=0;i<num;i++) {
                        putForNodeStartTag(node, saxHandler);
                       
                        NodeList nodeList = node.getChildNodes();
                        for(int j=0;j<nodeList.getLength();j++) {
                            Node node2 = nodeList.item(j);
                            putNode(node2, saxHandler, i+1);
                        }
                        putNodeEndTag(tagNameString, node, saxHandler);
                    }
                }
                else {
                    putNodeStartTag(node, saxHandler);
                    NodeList nodeList = node.getChildNodes();
                    for(int i=0;i<nodeList.getLength();i++) {
                        Node node2 = nodeList.item(i);
                        putNode(node2, saxHandler, no);
                    }
                    putNodeEndTag(node, saxHandler);
                }
                break;
        }
    }

    private void putNodeTextTag(Node node, TransformerHandler saxHandler, int no) throws SAXException {
        if(node.getNodeType() == Node.TEXT_NODE) {
            String s = node.getNodeValue().trim();
            String noString = Integer.toString(no);
            s = s.replaceAll("%s", noString);
            char
charMsg = s.toCharArray();
            saxHandler.characters(charMsg, 0, charMsg.length);
        }
    }
   
    private void putNodeStartTag(Node node, TransformerHandler saxHandler) throws SAXException {
        if(node.getNodeType() == Node.ELEMENT_NODE) {
            NamedNodeMap map = node.getAttributes();
            String tagNameString = node.getNodeName();
            AttributesImpl attributes = new AttributesImpl();
            for(int i=0;i<map.getLength();i++) {
                Node n = map.item(i);
                attributes.addAttribute("", n.getNodeName(), n.getNodeName(), "CDATA", n.getNodeValue());
            }
            saxHandler.startElement("", tagNameString, tagNameString, attributes);
        }
    }
   
   
    private void putNodeEndTag(Node node, TransformerHandler saxHandler) throws SAXException {
        if(node.getNodeType() == Node.ELEMENT_NODE) {
            String tagNameString = node.getNodeName();
            saxHandler.endElement("", tagNameString, tagNameString);
        }
    }

    private void putNodeEndTag(String tagName, Node node, TransformerHandler saxHandler) throws SAXException {
        if(node.getNodeType() == Node.ELEMENT_NODE) {
            saxHandler.endElement("", tagName, tagName);
        }
    }

    private void putForNodeStartTag(Node node, TransformerHandler saxHandler) throws SAXException {

        NamedNodeMap map = node.getAttributes();
        String tagNameString = map.getNamedItem("tagName").getNodeValue();

        AttributesImpl attributes = new AttributesImpl();
        for(int i=0;i<map.getLength();i++) {
            Node n = map.item(i);
            if(!n.getNodeName().equals("num") && !n.getNodeName().equals("tagName")) {
                attributes.addAttribute("", n.getNodeName(), n.getNodeName(), "CDATA", n.getNodeValue());
            }
        }
        saxHandler.startElement("", tagNameString, tagNameString, attributes);
    }
}

作成するデータの構造を指定するサンプルデータ(Test5.xml)
(forタグは属性tagNameの値の名前で属性numの数のタグを生成する。)

<?xml version="1.0" encoding="Shift_JIS" ?>
<students>
  <for num="2" tagName="school" Country="Japan">
    <name>SchoolName_%s</name>
    <for num="3" tagName="Student" department="engineering">
        <id>StudentID_%s</id>
        <name>StudentName_%s</name>
    </for>
  </for>
</students>

実行結果(result5.xml)

<?xml version="1.0" encoding="UTF-8"?>
<students>
  <school Country="Japan">
    <name>SchoolName_1</name>
    <Student department="engineering">
      <id>StudentID_1</id>
      <name>StudentName_1</name>
    </Student>
    <Student department="engineering">
      <id>StudentID_2</id>
      <name>StudentName_2</name>
    </Student>
    <Student department="engineering">
      <id>StudentID_3</id>
      <name>StudentName_3</name>
    </Student>
  </school>
  <school Country="Japan">
    <name>SchoolName_2</name>
    <Student department="engineering">
      <id>StudentID_1</id>
      <name>StudentName_1</name>
    </Student>
    <Student department="engineering">
      <id>StudentID_2</id>
      <name>StudentName_2</name>
    </Student>
    <Student department="engineering">
      <id>StudentID_3</id>
      <name>StudentName_3</name>
    </Student>
  </school>
</students>

 ここを参照しました。