Merge pull request 'xml-2 版本初始化提交' (#47) from xml-2 into main

Reviewed-on: https://src.isharkfly.com/iSharkFly-Docs/java-tutorials/pulls/47
This commit is contained in:
honeymoose
2025-04-30 15:53:52 +00:00
78 changed files with 2245 additions and 527 deletions
+7 -4
View File
@@ -4,12 +4,15 @@ This module contains articles about eXtensible Markup Language (XML)
### Relevant Articles:
- [Pretty-Print XML in Java](https://www.baeldung.com/java-pretty-print-xml)
- [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd)
- [Converting JSON to XML in Java](https://www.baeldung.com/java-convert-json-to-xml)
- [Convert an XML Object to a String in Java](https://www.baeldung.com/java-convert-xml-object-string)
- [Convert String Containing XML to org.w3c.dom.Document](https://www.baeldung.com/java-convert-string-xml-dom)
- [How to Parse XML to HashMap in Java](https://www.baeldung.com/java-xml-read-into-hashmap)
- [Convert an XML File to CSV File](https://www.baeldung.com/java-convert-xml-csv)
- [Invalid Characters in XML](https://www.baeldung.com/java-xml-invalid-characters)
- [How to Convert XML to PDF](https://www.baeldung.com/java-xml-pdf-conversion)
- [How to Convert org.w3c.dom.Document to String in Java](https://www.baeldung.com/java-convert-org-w3c-dom-document-string)
- [Introduction to JiBX](https://www.baeldung.com/jibx)
- [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file)
- [Modifying an XML Attribute in Java](https://www.baeldung.com/java-modify-xml-attribute)
- [Convert XML to HTML in Java](https://www.baeldung.com/java-convert-xml-to-html)
- - More articles: [[prev -->]](../xml)
+312 -22
View File
File diff suppressed because it is too large Load Diff
@@ -1,91 +0,0 @@
package com.baeldung.xml.prettyprint;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
public class XmlPrettyPrinter {
public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {
try {
final InputSource src = new InputSource(new StringReader(xmlString));
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(readPrettyPrintXslt())));
// Using the default transformer will create empty lines in Java9+
// Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Alternatively, we can set indent-size on the transformer object
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
Writer out = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(out));
return out.toString();
} catch (Exception e) {
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
}
}
public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
try {
final OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
format.setIndentSize(indent);
format.setSuppressDeclaration(skipDeclaration);
final org.dom4j.Document document = DocumentHelper.parseText(xmlString);
final StringWriter sw = new StringWriter();
final XMLWriter writer = new XMLWriter(sw, format);
writer.write(document);
return sw.toString();
} catch (Exception e) {
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
}
}
public static void main(String[] args) throws IOException {
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
String xmlString = readFromInputStream(inputStream);
System.out.println("Pretty printing by Transformer");
System.out.println("=============================================");
System.out.println(prettyPrintByTransformer(xmlString, 2, true));
System.out.println("=============================================");
System.out.println("Pretty printing by Dom4j");
System.out.println("=============================================");
System.out.println(prettyPrintByDom4j(xmlString, 8, false));
System.out.println("=============================================");
}
private static String readPrettyPrintXslt() throws IOException {
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl");
return readFromInputStream(inputStream);
}
private static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
return resultStringBuilder.toString();
}
}
@@ -1,35 +0,0 @@
package com.baeldung.xml.validation;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import java.util.ArrayList;
import java.util.List;
public class XmlErrorHandler implements ErrorHandler {
private List<SAXParseException> exceptions;
public XmlErrorHandler() {
this.exceptions = new ArrayList<>();
}
public List<SAXParseException> getExceptions() {
return exceptions;
}
@Override
public void warning(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void error(SAXParseException exception) {
exceptions.add(exception);
}
@Override
public void fatalError(SAXParseException exception) {
exceptions.add(exception);
}
}
@@ -1,62 +0,0 @@
package com.baeldung.xml.validation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class XmlValidator {
private static final Logger LOGGER = LoggerFactory.getLogger(XmlValidator.class);
private String xsdPath;
private String xmlPath;
public XmlValidator(String xsdPath, String xmlPath) {
this.xsdPath = xsdPath;
this.xmlPath = xmlPath;
}
public boolean isValid() throws IOException, SAXException {
Validator validator = initValidator(xsdPath);
try {
validator.validate(new StreamSource(getFile(xmlPath)));
return true;
} catch (SAXException e) {
return false;
}
}
public List<SAXParseException> listParsingExceptions() throws IOException, SAXException {
XmlErrorHandler xsdErrorHandler = new XmlErrorHandler();
Validator validator = initValidator(xsdPath);
validator.setErrorHandler(xsdErrorHandler);
try {
validator.validate(new StreamSource(getFile(xmlPath)));
} catch (SAXParseException e) {}
xsdErrorHandler.getExceptions().forEach(e -> LOGGER.info(String.format("Line number: %s, Column number: %s. %s", e.getLineNumber(), e.getColumnNumber(), e.getMessage())));
return xsdErrorHandler.getExceptions();
}
private Validator initValidator(String xsdPath) throws SAXException {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(getFile(xsdPath));
Schema schema = factory.newSchema(schemaFile);
return schema.newValidator();
}
private File getFile(String location) {
return new File(getClass().getClassLoader().getResource(location).getFile());
}
}
@@ -0,0 +1,36 @@
package com.isharkfly.xml;
import org.w3c.dom.Document;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class XMLDocumentWriter {
public void write(Document document, String fileName, boolean excludeDeclaration, boolean prettyPrint) {
try(FileWriter writer = new FileWriter(new File(fileName))) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
if(excludeDeclaration) {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
if(prettyPrint) {
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
} catch (IOException e) {
throw new IllegalArgumentException(e);
} catch (TransformerConfigurationException e) {
throw new IllegalStateException(e);
} catch (TransformerException e) {
throw new IllegalArgumentException(e);
}
}
}
@@ -0,0 +1,49 @@
package com.isharkfly.xml.attribute;
import org.dom4j.*;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
public class Dom4jTransformer {
private final Document input;
public Dom4jTransformer(String resourcePath) throws DocumentException, SAXException {
// 1- Build the doc from the XML file
SAXReader xmlReader = new SAXReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
this.input = xmlReader.read(resourcePath);
}
public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerException, TransformerException {
// 2- Locate the node(s) with xpath, we can use index and iterator too.
String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue);
XPath xpath = DocumentHelper.createXPath(expr);
List<Node> nodes = xpath.selectNodes(input);
// 3- Make the change on the selected nodes
for (int i = 0; i < nodes.size(); i++) {
Element element = (Element) nodes.get(i);
element.addAttribute(attribute, newValue);
}
// 4- Save the result to a new XML doc
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer xformer = factory.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
xformer.transform(new DocumentSource(input), new StreamResult(output));
return output.toString();
}
}
@@ -0,0 +1,60 @@
package com.isharkfly.xml.attribute;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
public class JaxpTransformer {
private Document input;
public JaxpTransformer(String resourcePath) throws SAXException, IOException, ParserConfigurationException {
// 1- Build the doc from the XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
this.input = factory.newDocumentBuilder()
.parse(resourcePath);
}
public String modifyAttribute(String attribute, String oldValue, String newValue)
throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException, TransformerConfigurationException {
// 2- Locate the node(s) with xpath
XPath xpath = XPathFactory.newInstance()
.newXPath();
NodeList nodes = (NodeList) xpath.evaluate(String.format("//*[contains(@%s, '%s')]", attribute, oldValue), this.input, XPathConstants.NODESET);
// 3- Make the change on the selected nodes
for (int i = 0; i < nodes.getLength(); i++) {
Element value = (Element) nodes.item(i);
value.setAttribute(attribute, newValue);
}
// Stream api syntax
// IntStream
// .range(0, nodes.getLength())
// .mapToObj(i -> (Element) nodes.item(i))
// .forEach(value -> value.setAttribute(attribute, newValue));
// 4- Save the result to a new XML doc
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer xformer = factory.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
xformer.transform(new DOMSource(this.input), new StreamResult(output));
return output.toString();
}
}
@@ -0,0 +1,38 @@
package com.isharkfly.xml.attribute;
import org.joox.JOOX;
import org.joox.Match;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.io.IOException;
import static org.joox.JOOX.$;
public class JooxTransformer {
private final Document input;
public JooxTransformer(String resourcePath) throws SAXException, IOException {
// 1- Build the doc from the XML file
DocumentBuilder builder = JOOX.builder();
input = builder.parse(resourcePath);
}
public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerFactoryConfigurationError {
// 2- Select the document
Match $ = $(input);
// 3 - Find node to modify
String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue);
$
// .find("to") or with xpath
.xpath(expr)
.get()
.stream()
.forEach(e -> e.setAttribute(attribute, newValue));
// 4- Return result as String
return $.toString();
}
}
@@ -0,0 +1,71 @@
package com.isharkfly.xml.attribute.jmh;
import com.isharkfly.xml.attribute.Dom4jTransformer;
import com.isharkfly.xml.attribute.JaxpTransformer;
import com.isharkfly.xml.attribute.JooxTransformer;
import org.dom4j.DocumentException;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class AttributeBenchMark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(AttributeBenchMark.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
@Benchmark
public String dom4jBenchmark() throws DocumentException, TransformerException, SAXException {
String path = this.getClass()
.getResource("/xml/attribute.xml")
.toString();
Dom4jTransformer transformer = new Dom4jTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
return transformer.modifyAttribute(attribute, oldValue, newValue);
}
@Benchmark
public String jooxBenchmark() throws IOException, SAXException {
String path = this.getClass()
.getResource("/xml/attribute.xml")
.toString();
JooxTransformer transformer = new JooxTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
return transformer.modifyAttribute(attribute, oldValue, newValue);
}
@Benchmark
public String jaxpBenchmark()
throws TransformerException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
String path = this.getClass()
.getResource("/xml/attribute.xml")
.toString();
JaxpTransformer transformer = new JaxpTransformer(path);
String attribute = "customer";
String oldValue = "true";
String newValue = "false";
return transformer.modifyAttribute(attribute, oldValue, newValue);
}
}
@@ -0,0 +1,53 @@
/*
* Customer.java 06.06.2008
*
* Copyright 2008 Stefan J&auml;ger
*
*/
package com.isharkfly.xml.jibx;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class Customer {
private Person person;
private String city;
private Phone homePhone;
private Phone officePhone;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Phone getHomePhone() {
return homePhone;
}
public void setHomePhone(Phone homePhone) {
this.homePhone = homePhone;
}
public Phone getOfficePhone() {
return officePhone;
}
public void setOfficePhone(Phone officePhone) {
this.officePhone = officePhone;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@@ -0,0 +1,14 @@
package com.isharkfly.xml.jibx;
public class Identity {
long customerId;
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
}
@@ -0,0 +1,25 @@
/*
* Person.java 06.06.2008
*
* Copyright 2008 Stefan J&auml;ger
*
*/
package com.isharkfly.xml.jibx;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class Person extends Identity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@@ -0,0 +1,14 @@
package com.isharkfly.xml.jibx;
public class Phone {
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
@@ -1,4 +1,4 @@
package com.baeldung.xml.tohashmap;
package com.isharkfly.xml.tohashmap;
public class Employee {
private String id;
@@ -1,9 +1,10 @@
package com.baeldung.xml.tohashmap;
package com.isharkfly.xml.tohashmap;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employees")
public class Employees {
@@ -1,4 +1,4 @@
package com.baeldung.xml.tohashmap;
package com.isharkfly.xml.tohashmap;
import java.io.IOException;
import java.io.StringReader;
@@ -9,9 +9,6 @@ import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -21,6 +18,9 @@ import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@@ -1,4 +1,4 @@
package com.baeldung.xml.xml2csv;
package com.isharkfly.xml.xml2csv;
import java.io.BufferedWriter;
import java.io.File;
@@ -0,0 +1,55 @@
package com.isharkfly.xml.xml2pdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class XmlToPdfConverter {
public static void convertXMLtoPDFUsingFop(String xmlFilePath, String xsltFilePath, String pdfFilePath) throws Exception {
// Initialize FOP
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// Specify output stream for PDF
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(new File(pdfFilePath).toPath()))) {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
// Create Transformer from XSLT
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(new File(xsltFilePath)));
// Apply transformation
Source src = new StreamSource(new File(xmlFilePath));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
}
}
public static void convertXMLtoPDFUsingIText(String xmlFilePath, String pdfFilePath) throws Exception {
try (FileOutputStream outputStream = new FileOutputStream(pdfFilePath)) {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
// Read XML content and add it to the Document
String xmlContent = new String(Files.readAllBytes(Paths.get(xmlFilePath)));
document.add(new Paragraph(xmlContent));
document.close();
}
}
}
@@ -0,0 +1,10 @@
package com.isharkfly.xmlhtml;
import com.isharkfly.xmlhtml.helpers.XMLRunner;
public class Application {
public static void main(String[] args) {
XMLRunner.doWork();
}
}
@@ -0,0 +1,22 @@
package com.isharkfly.xmlhtml;
public class Constants {
public static final String XML_FILE_IN = "src/main/resources/xml/in.xml";
public static final String JAXB_FILE_OUT = "src/main/resources/xml/jaxb.html";
public static final String JAXP_FILE_OUT = "src/main/resources/xml/jaxp.html";
public static final String STAX_FILE_OUT = "src/main/resources/xml/stax.html";
public static final String EXCEPTION_ENCOUNTERED = "Generic exception! Error: ";
public static final String LINE_BREAK = System.getProperty("line.separator");
public static final String WHITE_SPACE = " ";
public static final String DOCUMENT_START = "Document parsing has begun!";
public static final String DOCUMENT_END = "Document parsing has ended!";
public static final String ELEMENT_START = "Element parsing has begun!";
public static final String ELEMENT_END = "Element parsing has ended!";
public static final String BREAK = "\n";
public static final String TAB = "\t";
}
@@ -0,0 +1,40 @@
package com.isharkfly.xmlhtml.freemarker;
import com.isharkfly.xmlhtml.stax.StaxTransformer;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
public class FreemarkerTransformer {
private StaxTransformer staxTransformer;
private String templateDirectory;
private String templateFile;
public FreemarkerTransformer(StaxTransformer staxTransformer, String templateDirectory, String templateFile) {
this.staxTransformer = staxTransformer;
this.templateDirectory = templateDirectory;
this.templateFile = templateFile;
}
public String html() throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
cfg.setFallbackOnNullLoopVariable(false);
Template temp = cfg.getTemplate(templateFile);
try (Writer output = new StringWriter()) {
temp.process(staxTransformer.getMap(), output);
return output.toString();
}
}
}
@@ -0,0 +1,11 @@
package com.isharkfly.xmlhtml.helpers;
import com.isharkfly.xmlhtml.helpers.jaxb.JAXBHelper;
public class XMLRunner {
public static void doWork() {
JAXBHelper.example();
}
}
@@ -0,0 +1,76 @@
package com.isharkfly.xmlhtml.helpers.jaxb;
import com.isharkfly.xmlhtml.pojo.jaxb.html.ExampleHTML;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.Body;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.CustomElement;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.Meta;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.NestedElement;
import com.isharkfly.xmlhtml.pojo.jaxb.xml.XMLExample;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import java.io.File;
import static com.isharkfly.xmlhtml.Constants.*;
public class JAXBHelper {
private static void print(String xmlContent) {
System.out.println(xmlContent);
}
private static Unmarshaller getContextUnmarshaller(Class clazz) {
Unmarshaller unmarshaller = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
unmarshaller = context.createUnmarshaller();
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return unmarshaller;
}
private static Marshaller getContextMarshaller(Class clazz) {
Marshaller marshaller = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("jaxb.fragment", Boolean.TRUE);
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return marshaller;
}
public static void example() {
try {
XMLExample xml = (XMLExample) JAXBHelper.getContextUnmarshaller(XMLExample.class).unmarshal(new File(XML_FILE_IN));
JAXBHelper.print(xml.toString());
ExampleHTML html = new ExampleHTML();
Body body = new Body();
CustomElement customElement = new CustomElement();
NestedElement nested = new NestedElement();
CustomElement child = new CustomElement();
customElement.setValue("descendantOne: " + xml.getAncestor().getDescendantOne().getValue());
child.setValue("descendantThree: " + xml.getAncestor().getDescendantTwo().getDescendantThree().getValue());
nested.setCustomElement(child);
body.setCustomElement(customElement);
body.setNestedElement(nested);
Meta meta = new Meta();
meta.setTitle("example");
html.getHead().add(meta);
html.setBody(body);
JAXBHelper.getContextMarshaller(ExampleHTML.class).marshal(html, new File(JAXB_FILE_OUT));
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
}
}
@@ -0,0 +1,103 @@
package com.isharkfly.xmlhtml.jaxp;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
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.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public class JaxpTransformer {
private Document input;
private DocumentBuilderFactory factory;
public JaxpTransformer(String resourcePath) throws ParserConfigurationException, IOException, SAXException {
// 1- Build the doc from the XML file
factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
input = factory
.newDocumentBuilder()
.parse(resourcePath);
}
public String html() throws ParserConfigurationException, TransformerException, IOException {
Element xml = input.getDocumentElement();
Document doc = factory
.newDocumentBuilder()
.newDocument();
//Build Map
Map<String, String> map = buildMap(xml);
//Head
Element html = doc.createElement("html");
html.setAttribute("lang", "en");
Element head = buildHead(map, doc);
html.appendChild(head);
//Body
Element body = buildBody(map, doc);
html.appendChild(body);
doc.appendChild(html);
return String.format("<!DOCTYPE html>%n%s", applyTransformation(doc));
}
private String applyTransformation(Document doc) throws TransformerException, IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
try (Writer output = new StringWriter()) {
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(output));
return output.toString();
}
}
private Map<String, String> buildMap(Element xml) {
Map<String, String> map = new HashMap<>();
map.put("heading", xml
.getElementsByTagName("heading")
.item(0)
.getTextContent());
map.put("from", String.format("from: %s", xml
.getElementsByTagName("from")
.item(0)
.getTextContent()));
map.put("content", xml
.getElementsByTagName("content")
.item(0)
.getTextContent());
return map;
}
private Element buildHead(Map<String, String> map, Document doc) {
Element head = doc.createElement("head");
Element title = doc.createElement("title");
title.setTextContent(map.get("heading"));
head.appendChild(title);
return head;
}
private Element buildBody(Map<String, String> map, Document doc) {
Element body = doc.createElement("body");
Element from = doc.createElement("p");
from.setTextContent(map.get("from"));
Element success = doc.createElement("p");
success.setTextContent(map.get("content"));
body.appendChild(from);
body.appendChild(success);
return body;
}
}
@@ -0,0 +1,30 @@
package com.isharkfly.xmlhtml.mustache;
import com.isharkfly.xmlhtml.stax.StaxTransformer;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
public class MustacheTransformer {
private StaxTransformer staxTransformer;
private String templateFile;
public MustacheTransformer(StaxTransformer staxTransformer, String templateFile) {
this.staxTransformer = staxTransformer;
this.templateFile = templateFile;
}
public String html() throws IOException {
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(templateFile);
try (Writer output = new StringWriter()) {
mustache.execute(output, staxTransformer.getMap());
output.flush();
return output.toString();
}
}
}
@@ -0,0 +1,38 @@
package com.isharkfly.xmlhtml.pojo.jaxb.html;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.Body;
import com.isharkfly.xmlhtml.pojo.jaxb.html.elements.Meta;
import jakarta.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@XmlType(propOrder = {"head", "body"})
@XmlRootElement(name = "html")
public class ExampleHTML {
private List<Meta> head = new ArrayList<>();
private Body body;
public ExampleHTML() { }
public List<Meta> getHead() {
return head;
}
@XmlElementWrapper(name = "head")
@XmlElement(name = "meta")
public void setHead(List<Meta> head) {
this.head = head;
}
public Body getBody() {
return body;
}
@XmlElement(name = "body")
public void setBody(Body body) {
this.body = body;
}
}
@@ -0,0 +1,29 @@
package com.isharkfly.xmlhtml.pojo.jaxb.html.elements;
import jakarta.xml.bind.annotation.XmlElement;
public class Body {
private CustomElement customElement;
public CustomElement getCustomElement() {
return customElement;
}
@XmlElement(name = "p")
public void setCustomElement(CustomElement customElement) {
this.customElement = customElement;
}
private NestedElement nestedElement;
public NestedElement getNestedElement() {
return nestedElement;
}
@XmlElement(name = "div")
public void setNestedElement(NestedElement nestedElement) {
this.nestedElement = nestedElement;
}
}
@@ -0,0 +1,18 @@
package com.isharkfly.xmlhtml.pojo.jaxb.html.elements;
import jakarta.xml.bind.annotation.XmlValue;
public class CustomElement {
private String value;
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,30 @@
package com.isharkfly.xmlhtml.pojo.jaxb.html.elements;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlValue;
public class Meta {
private String title;
public String getTitle() {
return title;
}
@XmlAttribute(name = "title")
public void setTitle(String title) {
this.title = title;
}
private String value;
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

Some files were not shown because too many files have changed in this diff Show More