//-----------------------------------
// XML DOM Example
//-----------------------------------

import java.io.*;

//imports for JAXP - DOM
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;

// imposts for XML transform
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class XMLDotsDOM {

    static final String JAXP_SCHEMA_LANGUAGE =
            "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    static final String W3C_XML_SCHEMA =
            "http://www.w3.org/2001/XMLSchema";

    public static void main(String[] args) {
        XMLDotsDOM dp = new XMLDotsDOM();

        // Load XML into a DOM document in memory
        Document doc = dp.loadXML(new File("dots.xml"));

        // Traverse the document and process dot elements
        dp.traversal(doc);

        // Modify the document in memory by adding a new dot element
        dp.modify(doc);

        // Saving the modified document to XML
        dp.saveXML(new File("copie.xml"), doc);
    }

    private void addDot(int x, int y) {
        System.out.println("dot: " + x + ", " + y);
    }

    private Document loadXML(File file) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            // Build default non-validating DOM-parser
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);
            return document;
        } catch (SAXParseException spe) {
            // Error generated by the parser
            System.out.println("\n** Parsing error" + ", line " +
                    spe.getLineNumber() + ", uri " + spe.getSystemId());
            System.out.println("   " + spe.getMessage());

            // Use the contained exception, if any
            Exception x = spe;

            if (spe.getException() != null) {
                x = spe.getException();
            }

            x.printStackTrace();
        } catch (SAXException sxe) {
            // Error generated during parsing)
            Exception x = sxe;

            if (sxe.getException() != null) {
                x = sxe.getException();
            }

            x.printStackTrace();
        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
        }
        return null;
    }

    private void traversal(Document doc) {
        // Get the root
        Element root = doc.getDocumentElement();

        // Get all the DOT children
        NodeList dots = root.getElementsByTagName("dot");

        // Iterate through them
        for (int i = 0; i < dots.getLength(); i++) {
            Element dot = (Element) dots.item(i);
            // Get the X and Y attrs out of the dot node
            addDot(Integer.parseInt(dot.getAttribute("x")),
                    Integer.parseInt(dot.getAttribute("y")));
        }
    }

    private Document modify(Document doc) {
        Element root = doc.getDocumentElement();

        // Create a new dot node
        Element elem = doc.createElement("dot");

        // Append node to root
        root.appendChild(elem);

        // Set the attribute/value bindings in a node.
        elem.setAttribute("x", "12");
        elem.setAttribute("y", "34");

        return doc;
    }

    private void saveXML(File file, Document doc) {

        try {
            TransformerFactory tranFact = TransformerFactory.newInstance();
            Transformer tran = tranFact.newTransformer();
            DOMSource DSource = new DOMSource(doc);
            StreamResult SResult = new StreamResult(new FileOutputStream(file)); //new StreamResult(System.out);
            tran.transform(DSource, SResult);
        } catch (TransformerConfigurationException tce) {
            // Error generated by the parser
            System.out.println("\n** Transformer Factory error");
            System.out.println("   " + tce.getMessage());

            // Use the contained exception, if any
            Throwable x = tce;

            if (tce.getException() != null) {
                x = tce.getException();
            }

            x.printStackTrace();
        } catch (TransformerException te) {
            // Error generated by the parser
            System.out.println("\n** Transformation error");
            System.out.println("   " + te.getMessage());

            // Use the contained exception, if any
            Throwable x = te;

            if (te.getException() != null) {
                x = te.getException();
            }

            x.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
        }
    }
}