aboutsummaryrefslogtreecommitdiff
path: root/src/musichub/util/XMLHandler.java
blob: 4b6184211f6fa73800065edbf2555264db275ae3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package musichub.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;


public class XMLHandler {
    TransformerFactory transformerFactory;
    Transformer transformer;
    DocumentBuilderFactory documentFactory;
    DocumentBuilder documentBuilder;

    public XMLHandler() {
        try {
            transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
            documentFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentFactory.newDocumentBuilder();
        } catch (TransformerException | ParserConfigurationException tfe) {
            tfe.printStackTrace();
        }
    }

    public void createXMLFile(Document document, String filePath) {
        try {
            // create the xml file
            //transform the DOM Object to an XML File
            DOMSource domSource = new DOMSource(document);
            StreamResult streamResult = new StreamResult(new File(filePath));

            // If you use
            // StreamResult result = new StreamResult(System.out);
            // the output will be pushed to the standard output ...
            // You can use that for debugging

            transformer.transform(domSource, streamResult);

        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

    public Document createXMLDocument() {
        return documentBuilder.newDocument();
    }

    public NodeList parseXMLFile(String filePath) {
        NodeList elementNodes = null;
        try {
            Document document = documentBuilder.parse(new File(filePath));
            Element root = document.getDocumentElement();

            elementNodes = root.getChildNodes();
        } catch (SAXException | IOException e) {
            e.printStackTrace();
        }
        return elementNodes;
    }


}