xml-2 版本初始化提交 #47
@ -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)
|
||||
|
334
xml-2/pom.xml
334
xml-2/pom.xml
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>xml-2</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
@ -26,16 +26,6 @@
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>${json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
@ -52,14 +42,96 @@
|
||||
<version>${xstream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-impl</artifactId>
|
||||
<version>${jaxb.version}</version>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>fop</artifactId>
|
||||
<version>${fop.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>${xmlbeans.version}</version>
|
||||
<groupId>com.itextpdf</groupId>
|
||||
<artifactId>itextpdf</artifactId>
|
||||
<version>${itextpdf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>jibx-run</artifactId>
|
||||
<version>${jibx-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.xmlunit</groupId>
|
||||
<artifactId>xmlunit-assertj</artifactId>
|
||||
<version>${xmlunit-assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>joox-java-6</artifactId>
|
||||
<version>${joox.version}</version>
|
||||
</dependency>
|
||||
<!-- JMH Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
<version>${jaxen.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.freemarker</groupId>
|
||||
<artifactId>freemarker</artifactId>
|
||||
<version>${freemarker.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.xml.bind</groupId>
|
||||
<artifactId>jakarta.xml.bind-api</artifactId>
|
||||
<version>${jakarta.xml.bind-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.spullara.mustache.java</groupId>
|
||||
<artifactId>compiler</artifactId>
|
||||
<version>${mustache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-impl</artifactId>
|
||||
<version>${jaxb-impl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jaxb</groupId>
|
||||
<artifactId>jaxb-runtime</artifactId>
|
||||
<version>${jaxb-runtime.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-core</artifactId>
|
||||
<version>${jaxb-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.htmlparser.jericho</groupId>
|
||||
<artifactId>jericho-html</artifactId>
|
||||
<version>${jericho.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.htmlcleaner</groupId>
|
||||
<artifactId>htmlcleaner</artifactId>
|
||||
<version>${htmlcleaner.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>${jsoup.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -71,6 +143,14 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>maven-jibx-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@ -79,18 +159,228 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>maven-jibx-plugin</artifactId>
|
||||
<version>${maven-jibx-plugin.version}</version>
|
||||
<configuration>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<includes>*-binding.xml</includes>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>template-binding.xml</exclude>
|
||||
</excludes>
|
||||
<schemaBindingDirectory>src/main/resources</schemaBindingDirectory>
|
||||
<includeSchemaBindings>
|
||||
<includeSchemaBindings>*-binding.xml</includeSchemaBindings>
|
||||
</includeSchemaBindings>
|
||||
<verbose>true</verbose>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process-classes</id>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>bind</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>process-test-classes</id>
|
||||
<phase>process-test-classes</phase>
|
||||
<goals>
|
||||
<goal>test-bind</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.bcel</groupId>
|
||||
<artifactId>bcel</artifactId>
|
||||
<version>${bcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>schemaGen</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>maven-jibx-plugin</artifactId>
|
||||
<version>${maven-jibx-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-java-code-from-schema</id>
|
||||
<goals>
|
||||
<goal>schema-codegen</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<include>Order.xsd</include>
|
||||
</includes>
|
||||
<verbose>true</verbose>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>compile-binding</id>
|
||||
<goals>
|
||||
<goal>bind</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<directory>target/generated-sources</directory>
|
||||
<load>true</load>
|
||||
<validate>true</validate>
|
||||
<!--<verbose>true</verbose> -->
|
||||
<verify>true</verify>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>generate-test-code-from-schema</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>test-schema-codegen</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>compile-test-binding</id>
|
||||
<phase>process-test-classes</phase>
|
||||
<goals>
|
||||
<goal>test-bind</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<directory>target/generated-test-sources</directory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>CustomerTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>bindGen</id>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>maven-jibx-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jibx</groupId>
|
||||
<artifactId>maven-jibx-plugin</artifactId>
|
||||
<version>${maven-jibx-plugin.version}</version>
|
||||
<configuration>
|
||||
<directory>src/main/resources</directory>
|
||||
<includes>
|
||||
<includes>*-binding.xml</includes>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>template-binding.xml</exclude>
|
||||
</excludes>
|
||||
<schemaBindingDirectory>src/main/resources</schemaBindingDirectory>
|
||||
<includeSchemaBindings>
|
||||
<includeSchemaBindings>*-binding.xml</includeSchemaBindings>
|
||||
</includeSchemaBindings>
|
||||
<verbose>true</verbose>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process-classes</id>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>bind</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>process-test-classes</id>
|
||||
<phase>process-test-classes</phase>
|
||||
<goals>
|
||||
<goal>test-bind</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<!-- NOTE: We don't need a groupId specification because the group is org.apache.maven.plugins -->
|
||||
<!--...which is assumed by default. -->
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>
|
||||
jar-with-dependencies
|
||||
</descriptorRef>
|
||||
</descriptorRefs>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>
|
||||
com.baeldung.xml.jibx.JiBXDemoApplication
|
||||
</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id><!-- this is used for inheritance merges -->
|
||||
<phase>package</phase><!-- append to the packaging phase. -->
|
||||
<goals>
|
||||
<goal>attached</goal><!-- goals == mojos -->
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<dom4j.version>2.1.3</dom4j.version>
|
||||
<json.version>20240303</json.version>
|
||||
<underscore.version>1.89</underscore.version>
|
||||
<xstream.version>1.4.18</xstream.version>
|
||||
<jaxb.version>2.3.3</jaxb.version>
|
||||
<xmlbeans.version>5.0.2</xmlbeans.version>
|
||||
<log4j-core.version>2.12.4</log4j-core.version>
|
||||
<fop.version>2.9</fop.version>
|
||||
<itextpdf.version>5.5.13.3</itextpdf.version>
|
||||
<jibx-version>1.2.4.5</jibx-version>
|
||||
<bcel.version>6.7.0</bcel.version>
|
||||
<maven-jibx-plugin.version>1.3.1</maven-jibx-plugin.version>
|
||||
<commons-lang3.version>3.14.0</commons-lang3.version>
|
||||
<xmlunit-assertj.version>2.6.3</xmlunit-assertj.version>
|
||||
<joox.version>1.6.2</joox.version>
|
||||
<jaxen.version>1.2.0</jaxen.version>
|
||||
<freemarker.version>2.3.29</freemarker.version>
|
||||
<jakarta.xml.bind-api.version>4.0.2</jakarta.xml.bind-api.version>
|
||||
<mustache.version>0.9.6</mustache.version>
|
||||
<jaxb-core.version>2.3.0.1</jaxb-core.version>
|
||||
<jaxb-impl.version>4.0.4</jaxb-impl.version>
|
||||
<jaxb-runtime.version>4.0.3</jaxb-runtime.version>
|
||||
<jericho.version>3.4</jericho.version>
|
||||
<htmlcleaner.version>2.25</htmlcleaner.version>
|
||||
<jsoup.version>1.17.2</jsoup.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
36
xml-2/src/main/java/com/isharkfly/xml/XMLDocumentWriter.java
Normal file
36
xml-2/src/main/java/com/isharkfly/xml/XMLDocumentWriter.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
53
xml-2/src/main/java/com/isharkfly/xml/jibx/Customer.java
Normal file
53
xml-2/src/main/java/com/isharkfly/xml/jibx/Customer.java
Normal file
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Customer.java 06.06.2008
|
||||
*
|
||||
* Copyright 2008 Stefan Jä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);
|
||||
}
|
||||
}
|
14
xml-2/src/main/java/com/isharkfly/xml/jibx/Identity.java
Normal file
14
xml-2/src/main/java/com/isharkfly/xml/jibx/Identity.java
Normal file
@ -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;
|
||||
}
|
||||
}
|
25
xml-2/src/main/java/com/isharkfly/xml/jibx/Person.java
Normal file
25
xml-2/src/main/java/com/isharkfly/xml/jibx/Person.java
Normal file
@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Person.java 06.06.2008
|
||||
*
|
||||
* Copyright 2008 Stefan Jä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);
|
||||
}
|
||||
}
|
14
xml-2/src/main/java/com/isharkfly/xml/jibx/Phone.java
Normal file
14
xml-2/src/main/java/com/isharkfly/xml/jibx/Phone.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
10
xml-2/src/main/java/com/isharkfly/xmlhtml/Application.java
Normal file
10
xml-2/src/main/java/com/isharkfly/xmlhtml/Application.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
22
xml-2/src/main/java/com/isharkfly/xmlhtml/Constants.java
Normal file
22
xml-2/src/main/java/com/isharkfly/xmlhtml/Constants.java
Normal file
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.html.elements;
|
||||
|
||||
import jakarta.xml.bind.annotation.XmlElement;
|
||||
|
||||
public class NestedElement {
|
||||
|
||||
private CustomElement customElement;
|
||||
|
||||
public CustomElement getCustomElement() {
|
||||
return customElement;
|
||||
}
|
||||
|
||||
@XmlElement(name = "p")
|
||||
public void setCustomElement(CustomElement customElement) {
|
||||
this.customElement = customElement;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.xml;
|
||||
|
||||
import com.isharkfly.xmlhtml.pojo.jaxb.xml.elements.Ancestor;
|
||||
import jakarta.xml.bind.annotation.XmlElement;
|
||||
import jakarta.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement(name = "xmlexample")
|
||||
public class XMLExample {
|
||||
|
||||
private Ancestor ancestor;
|
||||
|
||||
@XmlElement(name = "ancestor")
|
||||
public void setAncestor(Ancestor ancestor) {
|
||||
this.ancestor = ancestor;
|
||||
}
|
||||
|
||||
public Ancestor getAncestor() {
|
||||
return ancestor;
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.xml.elements;
|
||||
|
||||
import jakarta.xml.bind.annotation.XmlElement;
|
||||
|
||||
public class Ancestor {
|
||||
|
||||
private DescendantOne descendantOne;
|
||||
private DescendantTwo descendantTwo;
|
||||
|
||||
public DescendantOne getDescendantOne() {
|
||||
return descendantOne;
|
||||
}
|
||||
|
||||
@XmlElement(name = "descendantOne")
|
||||
public void setDescendantOne(DescendantOne descendantOne) {
|
||||
this.descendantOne = descendantOne;
|
||||
}
|
||||
|
||||
public DescendantTwo getDescendantTwo() {
|
||||
return descendantTwo;
|
||||
}
|
||||
|
||||
@XmlElement(name = "descendantTwo")
|
||||
public void setDescendantTwo(DescendantTwo descendantTwo) {
|
||||
this.descendantTwo = descendantTwo;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,19 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.xml.elements;
|
||||
|
||||
import jakarta.xml.bind.annotation.XmlValue;
|
||||
|
||||
public class DescendantOne {
|
||||
|
||||
private String value;
|
||||
|
||||
@XmlValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,18 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.xml.elements;
|
||||
|
||||
import jakarta.xml.bind.annotation.XmlValue;
|
||||
|
||||
public class DescendantThree {
|
||||
|
||||
private String value;
|
||||
|
||||
@XmlValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.isharkfly.xmlhtml.pojo.jaxb.xml.elements;
|
||||
|
||||
import jakarta.xml.bind.annotation.XmlElement;
|
||||
|
||||
public class DescendantTwo {
|
||||
|
||||
private DescendantThree descendantThree;
|
||||
|
||||
public DescendantThree getDescendantThree() {
|
||||
return descendantThree;
|
||||
}
|
||||
|
||||
@XmlElement(name = "descendantThree")
|
||||
public void setDescendant(DescendantThree descendantThree) {
|
||||
this.descendantThree = descendantThree;
|
||||
}
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
package com.isharkfly.xmlhtml.stax;
|
||||
|
||||
import javax.xml.stream.*;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class StaxTransformer {
|
||||
|
||||
private Map<String, String> map;
|
||||
|
||||
public StaxTransformer(String resourcePath) throws IOException, XMLStreamException {
|
||||
XMLInputFactory factory = XMLInputFactory.newInstance();
|
||||
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
|
||||
factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
|
||||
XMLStreamReader input = null;
|
||||
try (FileInputStream file = new FileInputStream(resourcePath)) {
|
||||
input = factory.createXMLStreamReader(file);
|
||||
map = buildMap(input);
|
||||
} finally {
|
||||
if (input != null) {
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String html() throws XMLStreamException, IOException {
|
||||
try (Writer output = new StringWriter()) {
|
||||
XMLStreamWriter writer = XMLOutputFactory
|
||||
.newInstance()
|
||||
.createXMLStreamWriter(output);
|
||||
//Head
|
||||
writer.writeDTD("<!DOCTYPE html>");
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeStartElement("html");
|
||||
writer.writeAttribute("lang", "en");
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeStartElement("head");
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeDTD("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeStartElement("title");
|
||||
writer.writeCharacters(map.get("heading"));
|
||||
writer.writeEndElement();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeEndElement();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
//Body
|
||||
writer.writeStartElement("body");
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeStartElement("p");
|
||||
writer.writeCharacters(map.get("from"));
|
||||
writer.writeEndElement();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeStartElement("p");
|
||||
writer.writeCharacters(map.get("content"));
|
||||
writer.writeEndElement();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeEndElement();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.writeEndDocument();
|
||||
writer.writeCharacters(String.format("%n"));
|
||||
writer.flush();
|
||||
return output.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> buildMap(XMLStreamReader input) throws XMLStreamException {
|
||||
Map<String, String> tempMap = new HashMap<>();
|
||||
while (input.hasNext()) {
|
||||
input.next();
|
||||
if (input.isStartElement()) {
|
||||
if (input
|
||||
.getLocalName()
|
||||
.equals("heading")) {
|
||||
tempMap.put("heading", input.getElementText());
|
||||
}
|
||||
if (input
|
||||
.getLocalName()
|
||||
.equals("from")) {
|
||||
tempMap.put("from", String.format("from: %s", input.getElementText()));
|
||||
}
|
||||
if (input
|
||||
.getLocalName()
|
||||
.equals("content")) {
|
||||
tempMap.put("content", input.getElementText());
|
||||
}
|
||||
}
|
||||
}
|
||||
return tempMap;
|
||||
}
|
||||
|
||||
public Map<String, String> getMap() {
|
||||
return map;
|
||||
}
|
||||
}
|
26
xml-2/src/main/resources/customer-binding.xml
Normal file
26
xml-2/src/main/resources/customer-binding.xml
Normal file
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<binding>
|
||||
<mapping class="com.isharkfly.xml.jibx.Identity" abstract="true">
|
||||
<value name="customer-id" field="customerId" />
|
||||
</mapping>
|
||||
|
||||
<mapping name="customer" class="com.isharkfly.xml.jibx.Customer">
|
||||
<structure field="person" />
|
||||
<structure name="home-phone" field="homePhone" usage="optional" />
|
||||
<structure name="office-phone" field="officePhone" usage="optional" />
|
||||
<value name="city" field="city" />
|
||||
</mapping>
|
||||
|
||||
<mapping name="person" class="com.isharkfly.xml.jibx.Person"
|
||||
extends="com.isharkfly.xml.jibx.Identity">
|
||||
<structure map-as="com.isharkfly.xml.jibx.Identity" />
|
||||
<value name="name" field="name" />
|
||||
|
||||
</mapping>
|
||||
|
||||
<mapping class="com.isharkfly.xml.jibx.Phone" abstract="true">
|
||||
<value name="number" field="number" />
|
||||
</mapping>
|
||||
|
||||
|
||||
</binding>
|
5
xml-2/src/main/resources/xml/attribute.xml
Normal file
5
xml-2/src/main/resources/xml/attribute.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="true">john@email.com</to>
|
||||
<from>mary@email.com</from>
|
||||
</notification>
|
5
xml-2/src/main/resources/xml/attribute_expected.xml
Normal file
5
xml-2/src/main/resources/xml/attribute_expected.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="false">john@email.com</to>
|
||||
<from>mary@email.com</from>
|
||||
</notification>
|
11
xml-2/src/main/resources/xml/in.xml
Normal file
11
xml-2/src/main/resources/xml/in.xml
Normal file
@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<xmlexample>
|
||||
<ancestor>
|
||||
<descendantOne>Yo</descendantOne>
|
||||
<descendantTwo>
|
||||
<descendantThree>
|
||||
DustyOrb
|
||||
</descendantThree>
|
||||
</descendantTwo>
|
||||
</ancestor>
|
||||
</xmlexample>
|
14
xml-2/src/main/resources/xml/jaxb.html
Normal file
14
xml-2/src/main/resources/xml/jaxb.html
Normal file
@ -0,0 +1,14 @@
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<meta title="example"/>
|
||||
</head>
|
||||
<body>
|
||||
<p>descendantOne: Yo</p>
|
||||
<div>
|
||||
<p>descendantThree:
|
||||
DustyOrb
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
13
xml-2/src/main/resources/xml/jaxp.html
Normal file
13
xml-2/src/main/resources/xml/jaxp.html
Normal file
@ -0,0 +1,13 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<p>descendantOne: Yo</p>
|
||||
<div>
|
||||
<p>descendantThree:
|
||||
DustyOrb
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -1,11 +0,0 @@
|
||||
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
|
||||
<xsl:strip-space elements="*"/>
|
||||
<xsl:output method="xml" encoding="UTF-8"/>
|
||||
|
||||
<xsl:template match="@*|node()">
|
||||
<xsl:copy>
|
||||
<xsl:apply-templates select="@*|node()"/>
|
||||
</xsl:copy>
|
||||
</xsl:template>
|
||||
|
||||
</xsl:stylesheet>
|
15
xml-2/src/main/resources/xml/stax.html
Normal file
15
xml-2/src/main/resources/xml/stax.html
Normal file
@ -0,0 +1,15 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta></meta>
|
||||
</head>
|
||||
<body>
|
||||
<p>descendantOne: Yo</p>
|
||||
<div>
|
||||
<p>
|
||||
descendantThree:
|
||||
DustyOrb
|
||||
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<individual>
|
||||
<name>Baeldung</name>
|
||||
<address>
|
||||
<zip>00001</zip>
|
||||
<city>New York</city>
|
||||
</address>
|
||||
</individual>
|
@ -1,25 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<xs:element name="individual">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="name">
|
||||
<xs:simpleType>
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:maxLength value="5" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
</xs:element>
|
||||
<xs:element name="address">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="zip" type="xs:positiveInteger" />
|
||||
<xs:element name="city" type="xs:string" />
|
||||
<xs:element name="street" type="xs:string" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<xs:element name="individual">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="name" type="xs:string" />
|
||||
<xs:element name="address">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="zip" type="xs:positiveInteger" />
|
||||
<xs:element name="city" type="xs:string" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
26
xml-2/src/main/resources/xmltopdf/data-input.xml
Normal file
26
xml-2/src/main/resources/xmltopdf/data-input.xml
Normal file
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0"?>
|
||||
<Bookstores>
|
||||
<Bookstore id="S001">
|
||||
<Books>
|
||||
<Book id="B001" category="Fiction">
|
||||
<Title>Death and the Penguin</Title>
|
||||
<Author id="A001">Andrey Kurkov</Author>
|
||||
<Price>10.99</Price>
|
||||
</Book>
|
||||
<Book id="B002" category="Poetry">
|
||||
<Title>Kobzar</Title>
|
||||
<Author id="A002">Taras Shevchenko</Author>
|
||||
<Price>8.50</Price>
|
||||
</Book>
|
||||
</Books>
|
||||
</Bookstore>
|
||||
<Bookstore id="S002">
|
||||
<Books>
|
||||
<Book id="B003" category="Novel">
|
||||
<Title>Voroshilovgrad</Title>
|
||||
<Author id="A003">Serhiy Zhadan</Author>
|
||||
<Price>12.99</Price>
|
||||
</Book>
|
||||
</Books>
|
||||
</Bookstore>
|
||||
</Bookstores>
|
75
xml-2/src/main/resources/xmltopdf/style.xsl
Normal file
75
xml-2/src/main/resources/xmltopdf/style.xsl
Normal file
@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<xsl:stylesheet version="1.0"
|
||||
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
||||
xmlns:fo="http://www.w3.org/1999/XSL/Format">
|
||||
|
||||
<!-- Define the layout for the PDF -->
|
||||
<fo:layout-master-set>
|
||||
<fo:simple-page-master master-name="simpleA4"
|
||||
page-width="8.5in" page-height="11in" margin-top="0.5in"
|
||||
margin-bottom="0.5in" margin-left="0.5in" margin-right="0.5in">
|
||||
<fo:region-body margin-top="0.5in" margin-bottom="0.5in"/>
|
||||
</fo:simple-page-master>
|
||||
</fo:layout-master-set>
|
||||
|
||||
<!-- Define the content of the PDF -->
|
||||
<xsl:template match="/">
|
||||
<fo:root>
|
||||
<fo:layout-master-set>
|
||||
<fo:simple-page-master master-name="simpleA4">
|
||||
<fo:region-body margin="1in"/>
|
||||
</fo:simple-page-master>
|
||||
</fo:layout-master-set>
|
||||
<fo:page-sequence master-reference="simpleA4">
|
||||
<fo:flow flow-name="xsl-region-body">
|
||||
<fo:block font-size="18pt" font-weight="bold" text-align="center">
|
||||
Bookstore Inventory
|
||||
</fo:block>
|
||||
<fo:table table-layout="fixed" width="100%">
|
||||
<fo:table-column column-width="20%"/>
|
||||
<fo:table-column column-width="20%"/>
|
||||
<fo:table-column column-width="20%"/>
|
||||
<fo:table-column column-width="20%"/>
|
||||
<fo:table-header>
|
||||
<fo:table-row>
|
||||
<fo:table-cell border="solid 1px" padding="5pt" background-color="#CCCCCC">
|
||||
<fo:block>Bookstore ID</fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt" background-color="#CCCCCC">
|
||||
<fo:block>Book ID</fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt" background-color="#CCCCCC">
|
||||
<fo:block>Title</fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt" background-color="#CCCCCC">
|
||||
<fo:block>Author</fo:block>
|
||||
</fo:table-cell>
|
||||
</fo:table-row>
|
||||
</fo:table-header>
|
||||
<fo:table-body>
|
||||
<xsl:apply-templates select="//Book"/>
|
||||
</fo:table-body>
|
||||
</fo:table>
|
||||
</fo:flow>
|
||||
</fo:page-sequence>
|
||||
</fo:root>
|
||||
</xsl:template>
|
||||
|
||||
<xsl:template match="Book">
|
||||
<fo:table-row>
|
||||
<fo:table-cell border="solid 1px" padding="5pt">
|
||||
<fo:block><xsl:value-of select="ancestor::Bookstore/@id"/></fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt">
|
||||
<fo:block><xsl:value-of select="@id"/></fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt">
|
||||
<fo:block><xsl:value-of select="Title"/></fo:block>
|
||||
</fo:table-cell>
|
||||
<fo:table-cell border="solid 1px" padding="5pt">
|
||||
<fo:block><xsl:value-of select="Author"/></fo:block>
|
||||
</fo:table-cell>
|
||||
</fo:table-row>
|
||||
</xsl:template>
|
||||
|
||||
</xsl:stylesheet>
|
@ -1,77 +0,0 @@
|
||||
package com.baeldung.xml.json2xml;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
|
||||
import com.github.underscore.U;
|
||||
import org.json.JSONObject;
|
||||
import org.json.XML;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class JsonToXmlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenConvertToXMLUsingJsonJava_thenConverted() {
|
||||
String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}";
|
||||
JSONObject jsonObject = new JSONObject(jsonString);
|
||||
String xmlString = XML.toString(jsonObject);
|
||||
Assertions.assertEquals("<address><city>New York</city><street>Wall Street</street></address><name>John</name><age>20</age>", xmlString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenConvertToXMLUsingJackson_thenConverted() throws JsonProcessingException {
|
||||
String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}";
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(jsonString);
|
||||
String xmlString = new XmlMapper().writeValueAsString(jsonNode);
|
||||
Assertions.assertEquals("<ObjectNode><name>John</name><age>20</age><address><street>Wall Street</street><city>New York</city></address></ObjectNode>", xmlString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenConvertToXMLUsingJacksonWithXMLDeclarationAndRoot_thenConverted() throws JsonProcessingException {
|
||||
String jsonString = "{\"name\":\"John\", \"age\":20, \"address\":{\"street\":\"Wall Street\", \"city\":\"New York\"}}";
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(jsonString);
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
|
||||
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
|
||||
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
|
||||
String xmlString = xmlMapper.writer().withRootName("root").withDefaultPrettyPrinter().writeValueAsString(jsonNode);
|
||||
Assertions.assertEquals("<?xml version='1.1' encoding='UTF-8'?>" + System.lineSeparator() +
|
||||
"<root>" + System.lineSeparator() +
|
||||
" <name>John</name>" + System.lineSeparator() +
|
||||
" <age>20</age>" + System.lineSeparator() +
|
||||
" <address>" + System.lineSeparator() +
|
||||
" <street>Wall Street</street>" + System.lineSeparator() +
|
||||
" <city>New York</city>" + System.lineSeparator() +
|
||||
" </address>" + System.lineSeparator() +
|
||||
"</root>" + System.lineSeparator(), xmlString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenConvertToXMLUsingUnderscoreJava_thenConverted() {
|
||||
String jsonString = "{\"name\":\"John\", \"age\":20}";
|
||||
String xmlString = U.jsonToXml(jsonString);
|
||||
Assertions.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
||||
"<root>\n" +
|
||||
" <name>John</name>\n" +
|
||||
" <age number=\"true\">20</age>\n" +
|
||||
"</root>", xmlString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonString_whenConvertToXMLUsingUnderscoreJavaWithoutAttributes_thenConverted() {
|
||||
String jsonString = "{\"name\":\"John\", \"age\":20}";
|
||||
String xmlString = U.jsonToXml(jsonString, U.JsonToXmlMode.REMOVE_ATTRIBUTES);
|
||||
Assertions.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
||||
"<root>\n" +
|
||||
" <name>John</name>\n" +
|
||||
" <age>20</age>\n" +
|
||||
"</root>", xmlString);
|
||||
}
|
||||
}
|
||||
|
@ -1,35 +0,0 @@
|
||||
package com.baeldung.xml.validation;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class XmlValidatorUnitTest {
|
||||
|
||||
private static final String BAELDUNG_XML_PATH = "xml/validation/baeldung.xml";
|
||||
private static final String PERSON_XSD_PATH = "xml/validation/person.xsd";
|
||||
private static final String FULL_PERSON_XSD_PATH = "xml/validation/full-person.xsd";
|
||||
|
||||
@Test
|
||||
public void givenValidXML_WhenIsValid_ThenTrue() throws IOException, SAXException {
|
||||
assertTrue(new XmlValidator(PERSON_XSD_PATH, BAELDUNG_XML_PATH).isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidXML_WhenIsValid_ThenFalse() throws IOException, SAXException {
|
||||
assertFalse(new XmlValidator(FULL_PERSON_XSD_PATH, BAELDUNG_XML_PATH).isValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidXML_WhenListParsingExceptions_ThenNone() throws IOException, SAXException {
|
||||
assertEquals(0, new XmlValidator(PERSON_XSD_PATH, BAELDUNG_XML_PATH).listParsingExceptions().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidXML_WhenListParsingExceptions_ThenHasThree() throws IOException, SAXException {
|
||||
assertEquals(3, new XmlValidator(FULL_PERSON_XSD_PATH, BAELDUNG_XML_PATH).listParsingExceptions().size());
|
||||
}
|
||||
|
||||
}
|
@ -1,87 +0,0 @@
|
||||
package com.baeldung.xml2string;
|
||||
|
||||
import org.apache.xmlbeans.XmlException;
|
||||
import org.apache.xmlbeans.XmlObject;
|
||||
import org.apache.xmlbeans.XmlOptions;
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
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.StringWriter;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class XMLObjectToStringUnitTest {
|
||||
private Document document;
|
||||
|
||||
@Before
|
||||
public void setup() throws ParserConfigurationException {
|
||||
// Create a DocumentBuilder
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
|
||||
// Create a new Document
|
||||
document = builder.newDocument();
|
||||
|
||||
// Create the root element
|
||||
Element rootElement = document.createElement("root");
|
||||
document.appendChild(rootElement);
|
||||
|
||||
// Create child elements
|
||||
Element childElement1 = document.createElement("child1");
|
||||
Element childElement2 = document.createElement("child2");
|
||||
|
||||
// Add text content to the child elements
|
||||
childElement1.appendChild(document.createTextNode("This is child element 1"));
|
||||
childElement2.appendChild(document.createTextNode("This is child element 2"));
|
||||
|
||||
// Append child elements to the root element
|
||||
rootElement.appendChild(childElement1);
|
||||
rootElement.appendChild(childElement2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXMLDocument_whenUsingTransformer_thenConvertXMLToString() throws TransformerException {
|
||||
TransformerFactory transformerFactory = TransformerFactory.newInstance();
|
||||
Transformer transformer = transformerFactory.newTransformer();
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
|
||||
String result = stringWriter.toString();
|
||||
|
||||
assertTrue(result.contains("<root>"));
|
||||
assertTrue(result.contains("This is child element 1"));
|
||||
assertTrue(result.contains("This is child element 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXMLDocument_whenUsingXmlBeans_thenConvertXMLToString() {
|
||||
try {
|
||||
|
||||
XmlObject xmlObject = XmlObject.Factory.parse(document);
|
||||
|
||||
XmlOptions options = new XmlOptions();
|
||||
options.setSavePrettyPrint();
|
||||
options.setUseDefaultNamespace();
|
||||
options.setSaveAggressiveNamespaces();
|
||||
|
||||
String xmlString = xmlObject.xmlText(options);
|
||||
|
||||
xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + xmlString;
|
||||
|
||||
assertTrue(xmlString.contains("<root>"));
|
||||
assertTrue(xmlString.contains("This is child element 1"));
|
||||
assertTrue(xmlString.contains("This is child element 2"));
|
||||
} catch (XmlException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.isharkfly.xml;
|
||||
|
||||
import com.isharkfly.xml.XMLDocumentWriter;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.io.File;
|
||||
|
||||
public class XMLDocumentWriterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXMLDocumentWhenWriteIsCalledThenXMLIsWrittenToFile() throws Exception {
|
||||
Document document = createSampleDocument();
|
||||
new XMLDocumentWriter().write(document, "company_simple.xml", false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXMLDocumentWhenWriteIsCalledWithPrettyPrintThenFormattedXMLIsWrittenToFile() throws Exception {
|
||||
Document document = createSampleDocument();
|
||||
new XMLDocumentWriter().write(document, "company_prettyprinted.xml", false, true);
|
||||
}
|
||||
|
||||
private Document createSampleDocument() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
|
||||
Document document = documentBuilder.newDocument();
|
||||
Element companyElement = document.createElement("Company");
|
||||
document.appendChild(companyElement);
|
||||
Element departmentElement = document.createElement("Department");
|
||||
departmentElement.setAttribute("name", "Sales");
|
||||
companyElement.appendChild(departmentElement);
|
||||
Element employee1 = document.createElement("Employee");
|
||||
employee1.setAttribute("name", "John Smith");
|
||||
departmentElement.appendChild(employee1);
|
||||
Element employee2 = document.createElement("Employee");
|
||||
employee2.setAttribute("name", "Tim Dellor");
|
||||
departmentElement.appendChild(employee2);
|
||||
return document;
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() throws Exception {
|
||||
FileUtils.deleteQuietly(new File("company_simple.xml"));
|
||||
FileUtils.deleteQuietly(new File("company_prettyprinted.xml"));
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.isharkfly.xml.attribute;
|
||||
|
||||
import com.isharkfly.xml.attribute.Dom4jTransformer;
|
||||
import org.dom4j.DocumentException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactoryConfigurationError;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.xmlunit.assertj.XmlAssert.assertThat;
|
||||
|
||||
/**
|
||||
* Unit test for {@link Dom4jTransformer}.
|
||||
*/
|
||||
public class Dom4jProcessorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws TransformerFactoryConfigurationError, TransformerException, DocumentException, SAXException {
|
||||
String path = getClass().getResource("/xml/attribute.xml")
|
||||
.toString();
|
||||
Dom4jTransformer transformer = new Dom4jTransformer(path);
|
||||
String attribute = "customer";
|
||||
String oldValue = "true";
|
||||
String newValue = "false";
|
||||
|
||||
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
|
||||
|
||||
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException, SAXException {
|
||||
String path = getClass().getResource("/xml/attribute.xml")
|
||||
.toString();
|
||||
Dom4jTransformer transformer = new Dom4jTransformer(path);
|
||||
String attribute = "customer";
|
||||
String oldValue = "true";
|
||||
String newValue = "false";
|
||||
String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
|
||||
.toURI()))));
|
||||
|
||||
String result = transformer
|
||||
.modifyAttribute(attribute, oldValue, newValue)
|
||||
.replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11
|
||||
|
||||
assertThat(result).and(expectedXml)
|
||||
.areSimilar();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
|
||||
String path = getClass().getResource("/xml/xee_attribute.xml")
|
||||
.toString();
|
||||
|
||||
assertThatThrownBy(() -> {
|
||||
|
||||
new Dom4jTransformer(path);
|
||||
|
||||
}).isInstanceOf(DocumentException.class);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.isharkfly.xml.attribute;
|
||||
|
||||
import com.isharkfly.xml.attribute.JaxpTransformer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.xml.sax.SAXParseException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactoryConfigurationError;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.xmlunit.assertj.XmlAssert.assertThat;
|
||||
|
||||
/**
|
||||
* Unit test for {@link JaxpTransformer}.
|
||||
*/
|
||||
public class JaxpProcessorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
|
||||
String path = getClass().getResource("/xml/attribute.xml")
|
||||
.toString();
|
||||
JaxpTransformer transformer = new JaxpTransformer(path);
|
||||
String attribute = "customer";
|
||||
String oldValue = "true";
|
||||
String newValue = "false";
|
||||
|
||||
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
|
||||
|
||||
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
|
||||
String path = getClass().getResource("/xml/xee_attribute.xml")
|
||||
.toString();
|
||||
|
||||
assertThatThrownBy(() -> {
|
||||
|
||||
new JaxpTransformer(path);
|
||||
|
||||
}).isInstanceOf(SAXParseException.class);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.isharkfly.xml.attribute;
|
||||
|
||||
import com.isharkfly.xml.attribute.JooxTransformer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.xml.sax.SAXParseException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactoryConfigurationError;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.xmlunit.assertj.XmlAssert.assertThat;
|
||||
|
||||
/**
|
||||
* Unit test for {@link JooxTransformer}.
|
||||
*/
|
||||
public class JooxProcessorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, TransformerFactoryConfigurationError {
|
||||
String path = getClass().getResource("/xml/attribute.xml")
|
||||
.toString();
|
||||
JooxTransformer transformer = new JooxTransformer(path);
|
||||
String attribute = "customer";
|
||||
String oldValue = "true";
|
||||
String newValue = "false";
|
||||
|
||||
String result = transformer.modifyAttribute(attribute, oldValue, newValue);
|
||||
|
||||
assertThat(result).hasXPath("//*[contains(@customer, 'false')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, URISyntaxException, SAXException {
|
||||
String path = getClass().getResource("/xml/attribute.xml")
|
||||
.toString();
|
||||
JooxTransformer transformer = new JooxTransformer(path);
|
||||
String attribute = "customer";
|
||||
String oldValue = "true";
|
||||
String newValue = "false";
|
||||
String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
|
||||
.toURI()))));
|
||||
|
||||
String result = transformer
|
||||
.modifyAttribute(attribute, oldValue, newValue)
|
||||
.replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11
|
||||
|
||||
assertThat(result).and(expectedXml)
|
||||
.areSimilar();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlXee_whenInit_thenThrowException() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
|
||||
String path = getClass().getResource("/xml/xee_attribute.xml")
|
||||
.toString();
|
||||
|
||||
assertThatThrownBy(() -> {
|
||||
|
||||
new JooxTransformer(path);
|
||||
|
||||
}).isInstanceOf(SAXParseException.class);
|
||||
}
|
||||
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.xml.invalidcharacters;
|
||||
package com.isharkfly.xml.invalidcharacters;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.InputSource;
|
@ -0,0 +1,53 @@
|
||||
package com.isharkfly.xml.jibx;
|
||||
|
||||
import com.isharkfly.xml.jibx.Customer;
|
||||
import org.jibx.runtime.BindingDirectory;
|
||||
import org.jibx.runtime.IBindingFactory;
|
||||
import org.jibx.runtime.IUnmarshallingContext;
|
||||
import org.jibx.runtime.JiBXException;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
|
||||
public class CustomerUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUnmarshalXML_ThenFieldsAreMapped() throws JiBXException, FileNotFoundException {
|
||||
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
|
||||
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
|
||||
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
|
||||
|
||||
assertEquals("Stefan Jaeger", customer.getPerson().getName());
|
||||
assertEquals("Davos Dorf", customer.getCity());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenUnmarshal_ThenMappingInherited() throws JiBXException, FileNotFoundException {
|
||||
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
|
||||
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
|
||||
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
|
||||
|
||||
assertEquals(12345, customer.getPerson().getCustomerId());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenUnmarshal_ThenPhoneMappingRead() throws JiBXException, FileNotFoundException {
|
||||
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
|
||||
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
|
||||
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
InputStream inputStream = classLoader.getResourceAsStream("Customer1.xml");
|
||||
Customer customer = (Customer) uctx.unmarshalDocument(inputStream, null);
|
||||
|
||||
assertEquals("234678", customer.getHomePhone().getNumber());
|
||||
|
||||
}
|
||||
}
|
@ -1,13 +1,13 @@
|
||||
package com.baeldung.xml.tohashmap;
|
||||
package com.isharkfly.xml.tohashmap;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
import com.isharkfly.xml.tohashmap.Employee;
|
||||
import com.isharkfly.xml.tohashmap.XmlToHashMap;
|
||||
import jakarta.xml.bind.JAXBException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.xml.xml2csv;
|
||||
package com.isharkfly.xml.xml2csv;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
@ -18,6 +18,7 @@ import java.util.concurrent.Executors;
|
||||
|
||||
import javax.xml.transform.TransformerException;
|
||||
|
||||
import com.isharkfly.xml.xml2csv.Xml2CsvExample;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
@ -1,37 +1,37 @@
|
||||
package com.baeldung.xml2document;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.*;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class XMLStringToDocumentObjectUnitTest {
|
||||
@Test
|
||||
public void givenValidXMLString_whenParsing_thenDocumentIsCorrect() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
String xmlString = "<root><element>XML Parsing Example</element></root>";
|
||||
InputSource is = new InputSource(new StringReader(xmlString));
|
||||
Document xmlDoc = null;
|
||||
try {
|
||||
xmlDoc = builder.parse(is);
|
||||
} catch (SAXException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
assertEquals("root", xmlDoc.getDocumentElement().getNodeName());
|
||||
assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName());
|
||||
assertEquals("XML Parsing Example", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent());
|
||||
}
|
||||
}
|
||||
package com.isharkfly.xml.xml2document;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.*;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class XMLStringToDocumentObjectUnitTest {
|
||||
@Test
|
||||
public void givenValidXMLString_whenParsing_thenDocumentIsCorrect() throws ParserConfigurationException {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
String xmlString = "<root><element>XML Parsing Example</element></root>";
|
||||
InputSource is = new InputSource(new StringReader(xmlString));
|
||||
Document xmlDoc = null;
|
||||
try {
|
||||
xmlDoc = builder.parse(is);
|
||||
} catch (SAXException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
assertEquals("root", xmlDoc.getDocumentElement().getNodeName());
|
||||
assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName());
|
||||
assertEquals("XML Parsing Example", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent());
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.isharkfly.xml.xml2pdf;
|
||||
|
||||
import com.isharkfly.xml.xml2pdf.XmlToPdfConverter;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class XmlToPdfConverterUnitTest {
|
||||
|
||||
private static final String BASE_PATH = "src/main/resources/xmltopdf/";
|
||||
|
||||
private static final String STYLE_XSL = BASE_PATH + "style.xsl";
|
||||
private static final String DATA_XML_INPUT = BASE_PATH + "data-input.xml";
|
||||
private static final String DATA_PDF_OUTPUT = BASE_PATH + "data-output.pdf";
|
||||
|
||||
// Comment out this method if you need to keep the outputted PDF file.
|
||||
@AfterEach
|
||||
public void teardown() {
|
||||
new File(DATA_PDF_OUTPUT).delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlFile_whenConvertToPdfUsingFop_thenPdfGenerated() throws Exception {
|
||||
// Execute XML to PDF conversion
|
||||
XmlToPdfConverter.convertXMLtoPDFUsingFop(DATA_XML_INPUT, STYLE_XSL, DATA_PDF_OUTPUT);
|
||||
// Check if PDF file was created
|
||||
File pdfFile = new File(DATA_PDF_OUTPUT);
|
||||
assertTrue(pdfFile.exists());
|
||||
assertTrue(pdfFile.isFile());
|
||||
assertTrue(pdfFile.length() > 0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenXmlFile_whenConvertToPdfUsingIText_thenPdfGenerated() throws Exception {
|
||||
// Execute XML to PDF conversion
|
||||
XmlToPdfConverter.convertXMLtoPDFUsingIText(DATA_XML_INPUT, DATA_PDF_OUTPUT);
|
||||
// Check if PDF file was created
|
||||
File pdfFile = new File(DATA_PDF_OUTPUT);
|
||||
assertTrue(pdfFile.exists());
|
||||
assertTrue(pdfFile.isFile());
|
||||
assertTrue(pdfFile.length() > 0);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.isharkfly.xmlhtml.delhtmltags;
|
||||
|
||||
import net.htmlparser.jericho.Renderer;
|
||||
import net.htmlparser.jericho.Segment;
|
||||
import net.htmlparser.jericho.Source;
|
||||
import org.htmlcleaner.CleanerProperties;
|
||||
import org.htmlcleaner.HtmlCleaner;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
class RemoveHtmlTagsLiveTest {
|
||||
|
||||
@Test
|
||||
void givenHtml1_whenRemoveTagsByRegex_thenPrintText() throws IOException, URISyntaxException {
|
||||
String html = new String(Files.readAllBytes(
|
||||
(Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example1.html").toURI()))));
|
||||
String result = html.replaceAll("<[^>]*>", "")
|
||||
.replaceAll("(?m)^\\s*$", ""); // remove empty and blank lines
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHtml2_whenRemoveTagsByRegex_thenPrintText() throws IOException, URISyntaxException {
|
||||
String html = new String(Files.readAllBytes(
|
||||
(Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI()))));
|
||||
String result = html.replaceAll("<[^>]*>", "");
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHtml2_whenRemoveTagsByJsoup_thenPrintText() throws IOException, URISyntaxException {
|
||||
String html = new String(Files.readAllBytes(
|
||||
(Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI()))));
|
||||
System.out.println(Jsoup.parse(html).text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHtml2_whenRemoveTagsByHtmlCleaner_thenPrintText() throws IOException, URISyntaxException {
|
||||
String html = new String(Files.readAllBytes(
|
||||
(Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI()))));
|
||||
CleanerProperties props = new CleanerProperties();
|
||||
props.setPruneTags("script");
|
||||
String result = new HtmlCleaner(props).clean(html).getText().toString();
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenHtml2_whenRemoveTagsByJericho_thenPrintText() throws IOException, URISyntaxException {
|
||||
String html = new String(Files.readAllBytes(
|
||||
(Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI()))));
|
||||
Source htmlSource = new Source(html);
|
||||
Segment segment = new Segment(htmlSource, 0, htmlSource.length());
|
||||
Renderer htmlRender = new Renderer(segment).setIncludeHyperlinkURLs(true);
|
||||
System.out.println(htmlRender);
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.isharkfly.xmlhtml.freemarker;
|
||||
|
||||
import com.isharkfly.xmlhtml.freemarker.FreemarkerTransformer;
|
||||
import com.isharkfly.xmlhtml.stax.StaxTransformer;
|
||||
import freemarker.template.TemplateException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class FreemarkerTransformerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException, TemplateException {
|
||||
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
|
||||
.getResource("/xmlhtml/notification.html")
|
||||
.toURI()))));
|
||||
StaxTransformer staxTransformer = new StaxTransformer("src/test/resources/xmlhtml/notification.xml");
|
||||
String templateFile = "freemarker.html";
|
||||
String templateDirectory = "src/test/resources/templates";
|
||||
FreemarkerTransformer transformer = new FreemarkerTransformer(staxTransformer, templateDirectory, templateFile);
|
||||
|
||||
String result = transformer.html();
|
||||
|
||||
assertThat(result).isEqualTo(expectedHtml);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.isharkfly.xmlhtml.jaxp;
|
||||
|
||||
import com.isharkfly.xmlhtml.jaxp.JaxpTransformer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JaxpTransformerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXml_whenTransform_thenGetHtml() throws IOException, SAXException, ParserConfigurationException, TransformerException, URISyntaxException {
|
||||
String path = getClass()
|
||||
.getResource("/xmlhtml/notification.xml")
|
||||
.toString();
|
||||
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
|
||||
.getResource("/xmlhtml/notification.html")
|
||||
.toURI()))));
|
||||
JaxpTransformer transformer = new JaxpTransformer(path);
|
||||
|
||||
String result = transformer
|
||||
.html()
|
||||
.replaceAll("(?m)^\\s+", "");//Delete extra spaces added by Java 11
|
||||
|
||||
assertThat(result).isEqualTo(expectedHtml);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.isharkfly.xmlhtml.mustache;
|
||||
|
||||
import com.isharkfly.xmlhtml.mustache.MustacheTransformer;
|
||||
import com.isharkfly.xmlhtml.stax.StaxTransformer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MustacheTransformerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException {
|
||||
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
|
||||
.getResource("/xmlhtml/notification.html")
|
||||
.toURI()))));
|
||||
StaxTransformer staxTransformer = new StaxTransformer("src/test/resources/xmlhtml/notification.xml");
|
||||
String templateFile = "src/test/resources/templates/template.mustache";
|
||||
MustacheTransformer transformer = new MustacheTransformer(staxTransformer, templateFile);
|
||||
|
||||
String result = transformer.html();
|
||||
|
||||
assertThat(result).isEqualTo(expectedHtml);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.isharkfly.xmlhtml.stax;
|
||||
|
||||
import com.isharkfly.xmlhtml.stax.StaxTransformer;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StaxTransformerUnitTest {
|
||||
|
||||
@Disabled // JAVA-39223
|
||||
@Test
|
||||
public void givenXml_whenTransform_thenGetHtml() throws IOException, URISyntaxException, XMLStreamException {
|
||||
String path = "src/test/resources/xmlhtml/notification.xml";
|
||||
String expectedHtml = new String(Files.readAllBytes((Paths.get(getClass()
|
||||
.getResource("/xmlhtml/notification.html")
|
||||
.toURI()))));
|
||||
StaxTransformer transformer = new StaxTransformer(path);
|
||||
|
||||
String result = transformer.html();
|
||||
|
||||
assertThat(result).isEqualTo(expectedHtml);
|
||||
}
|
||||
|
||||
}
|
16
xml-2/src/test/resources/Customer1.xml
Normal file
16
xml-2/src/test/resources/Customer1.xml
Normal file
@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<customer>
|
||||
<person>
|
||||
<customer-id>12345</customer-id>
|
||||
<name>Stefan Jaeger</name>
|
||||
</person>
|
||||
<home-phone>
|
||||
<number>234678</number>
|
||||
</home-phone>
|
||||
|
||||
<office-phone>
|
||||
<number>234678</number>
|
||||
</office-phone>
|
||||
<city>Davos Dorf</city>
|
||||
|
||||
</customer>
|
11
xml-2/src/test/resources/templates/freemarker.html
Normal file
11
xml-2/src/test/resources/templates/freemarker.html
Normal file
@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>${heading}</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>${from}</p>
|
||||
<p>${content}</p>
|
||||
</body>
|
||||
</html>
|
11
xml-2/src/test/resources/templates/template.mustache
Normal file
11
xml-2/src/test/resources/templates/template.mustache
Normal file
@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>{{heading}}</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>{{from}}</p>
|
||||
<p>{{content}}</p>
|
||||
</body>
|
||||
</html>
|
5
xml-2/src/test/resources/xml/attribute.xml
Normal file
5
xml-2/src/test/resources/xml/attribute.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="true">john@email.com</to>
|
||||
<from>mary@email.com</from>
|
||||
</notification>
|
5
xml-2/src/test/resources/xml/attribute_expected.xml
Normal file
5
xml-2/src/test/resources/xml/attribute_expected.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="false">john@email.com</to>
|
||||
<from>mary@email.com</from>
|
||||
</notification>
|
9
xml-2/src/test/resources/xml/xee_attribute.xml
Normal file
9
xml-2/src/test/resources/xml/xee_attribute.xml
Normal file
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE notification [
|
||||
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
|
||||
<notification id="5">
|
||||
<bad_entry>&xxe;
|
||||
</bad_entry>
|
||||
<to customer="true">john@email.com</to>
|
||||
<from>mary@email.com</from>
|
||||
</notification>
|
15
xml-2/src/test/resources/xmlhtml/delhtmltags/example1.html
Normal file
15
xml-2/src/test/resources/xmlhtml/delhtmltags/example1.html
Normal file
@ -0,0 +1,15 @@
|
||||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
||||
"http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<title>This is the page title</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
If the application X doesn't start, the possible causes could be:<br/>
|
||||
1. <a href="maven.com">Maven</a> is not installed.<br/>
|
||||
2. Not enough disk space.<br/>
|
||||
3. Not enough memory.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
22
xml-2/src/test/resources/xmlhtml/delhtmltags/example2.html
Normal file
22
xml-2/src/test/resources/xmlhtml/delhtmltags/example2.html
Normal file
@ -0,0 +1,22 @@
|
||||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
||||
"http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<title>This is the page title</title>
|
||||
</head>
|
||||
<script>
|
||||
// some interesting script functions
|
||||
</script>
|
||||
<body>
|
||||
<p>
|
||||
If the application X doesn't start, the possible causes could be:<br/>
|
||||
1. <a
|
||||
id="link"
|
||||
href="http://maven.apache.org/">
|
||||
Maven
|
||||
</a> is not installed.<br/>
|
||||
2. Not enough (<1G) disk space.<br/>
|
||||
3. Not enough (<64MB) memory.<br/>
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
11
xml-2/src/test/resources/xmlhtml/notification.html
Normal file
11
xml-2/src/test/resources/xmlhtml/notification.html
Normal file
@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>Build #7 passed</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>from: builds@baeldung.com</p>
|
||||
<p>Success: The Jenkins CI build passed</p>
|
||||
</body>
|
||||
</html>
|
6
xml-2/src/test/resources/xmlhtml/notification.xml
Normal file
6
xml-2/src/test/resources/xmlhtml/notification.xml
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification>
|
||||
<from>builds@baeldung.com</from>
|
||||
<heading>Build #7 passed</heading>
|
||||
<content>Success: The Jenkins CI build passed</content>
|
||||
</notification>
|
Loading…
x
Reference in New Issue
Block a user