|
| 1 | +package com.baeldung.xml; |
| 2 | + |
| 3 | +import javax.xml.parsers.DocumentBuilder; |
| 4 | +import javax.xml.parsers.DocumentBuilderFactory; |
| 5 | +import javax.xml.parsers.ParserConfigurationException; |
| 6 | + |
| 7 | +import org.apache.commons.io.FileUtils; |
| 8 | +import org.junit.After; |
| 9 | +import org.junit.Test; |
| 10 | +import org.w3c.dom.Document; |
| 11 | +import org.w3c.dom.Element; |
| 12 | + |
| 13 | +import java.io.File; |
| 14 | + |
| 15 | +public class XMLDocumentWriterUnitTest { |
| 16 | + |
| 17 | + @Test |
| 18 | + public void givenXMLDocumentWhenWriteIsCalledThenXMLIsWrittenToFile() throws Exception { |
| 19 | + Document document = createSampleDocument(); |
| 20 | + new XMLDocumentWriter().write(document, "company_simple.xml", false, false); |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + public void givenXMLDocumentWhenWriteIsCalledWithPrettyPrintThenFormattedXMLIsWrittenToFile() throws Exception { |
| 25 | + Document document = createSampleDocument(); |
| 26 | + new XMLDocumentWriter().write(document, "company_prettyprinted.xml", false, true); |
| 27 | + } |
| 28 | + |
| 29 | + private Document createSampleDocument() throws ParserConfigurationException { |
| 30 | + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); |
| 31 | + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); |
| 32 | + Document document = documentBuilder.newDocument(); |
| 33 | + Element companyElement = document.createElement("Company"); |
| 34 | + document.appendChild(companyElement); |
| 35 | + Element departmentElement = document.createElement("Department"); |
| 36 | + departmentElement.setAttribute("name", "Sales"); |
| 37 | + companyElement.appendChild(departmentElement); |
| 38 | + Element employee1 = document.createElement("Employee"); |
| 39 | + employee1.setAttribute("name", "John Smith"); |
| 40 | + departmentElement.appendChild(employee1); |
| 41 | + Element employee2 = document.createElement("Employee"); |
| 42 | + employee2.setAttribute("name", "Tim Dellor"); |
| 43 | + departmentElement.appendChild(employee2); |
| 44 | + return document; |
| 45 | + } |
| 46 | + |
| 47 | + @After |
| 48 | + public void cleanUp() throws Exception { |
| 49 | + FileUtils.deleteQuietly(new File("company_simple.xml")); |
| 50 | + FileUtils.deleteQuietly(new File("company_prettyprinted.xml")); |
| 51 | + } |
| 52 | +} |
0 commit comments