Merge from remote
This commit is contained in:
+7
-4
@@ -4,12 +4,15 @@ This module contains articles about eXtensible Markup Language (XML)
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Pretty-Print XML in Java](https://www.baeldung.com/java-pretty-print-xml)
|
||||
- [Validate an XML File Against an XSD File](https://www.baeldung.com/java-validate-xml-xsd)
|
||||
- [Converting JSON to XML in Java](https://www.baeldung.com/java-convert-json-to-xml)
|
||||
- [Convert an XML Object to a String in Java](https://www.baeldung.com/java-convert-xml-object-string)
|
||||
- [Convert String Containing XML to org.w3c.dom.Document](https://www.baeldung.com/java-convert-string-xml-dom)
|
||||
- [How to Parse XML to HashMap in Java](https://www.baeldung.com/java-xml-read-into-hashmap)
|
||||
- [Convert an XML File to CSV File](https://www.baeldung.com/java-convert-xml-csv)
|
||||
- [Invalid Characters in XML](https://www.baeldung.com/java-xml-invalid-characters)
|
||||
- [How to Convert XML to PDF](https://www.baeldung.com/java-xml-pdf-conversion)
|
||||
- [How to Convert org.w3c.dom.Document to String in Java](https://www.baeldung.com/java-convert-org-w3c-dom-document-string)
|
||||
- [Introduction to JiBX](https://www.baeldung.com/jibx)
|
||||
- [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file)
|
||||
- [Modifying an XML Attribute in Java](https://www.baeldung.com/java-modify-xml-attribute)
|
||||
- [Convert XML to HTML in Java](https://www.baeldung.com/java-convert-xml-to-html)
|
||||
|
||||
- - More articles: [[prev -->]](../xml)
|
||||
|
||||
+312
-22
File diff suppressed because it is too large
Load Diff
@@ -1,91 +0,0 @@
|
||||
package com.baeldung.xml.prettyprint;
|
||||
|
||||
import org.dom4j.DocumentHelper;
|
||||
import org.dom4j.io.OutputFormat;
|
||||
import org.dom4j.io.XMLWriter;
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
import java.io.*;
|
||||
|
||||
public class XmlPrettyPrinter {
|
||||
|
||||
public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {
|
||||
|
||||
try {
|
||||
final InputSource src = new InputSource(new StringReader(xmlString));
|
||||
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
|
||||
|
||||
TransformerFactory transformerFactory = TransformerFactory.newInstance();
|
||||
transformerFactory.setAttribute("indent-number", indent);
|
||||
Transformer transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(readPrettyPrintXslt())));
|
||||
// Using the default transformer will create empty lines in Java9+
|
||||
// Transformer transformer = transformerFactory.newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
// Alternatively, we can set indent-size on the transformer object
|
||||
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
|
||||
Writer out = new StringWriter();
|
||||
transformer.transform(new DOMSource(document), new StreamResult(out));
|
||||
return out.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
|
||||
try {
|
||||
final OutputFormat format = OutputFormat.createPrettyPrint();
|
||||
format.setEncoding("UTF-8");
|
||||
format.setIndentSize(indent);
|
||||
format.setSuppressDeclaration(skipDeclaration);
|
||||
|
||||
final org.dom4j.Document document = DocumentHelper.parseText(xmlString);
|
||||
final StringWriter sw = new StringWriter();
|
||||
final XMLWriter writer = new XMLWriter(sw, format);
|
||||
writer.write(document);
|
||||
return sw.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
|
||||
String xmlString = readFromInputStream(inputStream);
|
||||
System.out.println("Pretty printing by Transformer");
|
||||
System.out.println("=============================================");
|
||||
System.out.println(prettyPrintByTransformer(xmlString, 2, true));
|
||||
System.out.println("=============================================");
|
||||
System.out.println("Pretty printing by Dom4j");
|
||||
System.out.println("=============================================");
|
||||
System.out.println(prettyPrintByDom4j(xmlString, 8, false));
|
||||
System.out.println("=============================================");
|
||||
}
|
||||
|
||||
|
||||
private static String readPrettyPrintXslt() throws IOException {
|
||||
InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/prettyprint.xsl");
|
||||
return readFromInputStream(inputStream);
|
||||
}
|
||||
|
||||
private static String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.baeldung.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 {
|
||||
|
||||
@@ -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,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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.xml;
|
||||
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@ import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
import jakarta.xml.bind.JAXBException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -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
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.xml2document;
|
||||
package com.baeldung.xml.xml2document;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.*;
|
||||
|
||||
@@ -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,61 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.xmlhtml.freemarker;
|
||||
|
||||
import com.baeldung.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,33 @@
|
||||
package com.baeldung.xmlhtml.jaxp;
|
||||
|
||||
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,30 @@
|
||||
package com.baeldung.xmlhtml.mustache;
|
||||
|
||||
import com.baeldung.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,30 @@
|
||||
package com.baeldung.xmlhtml.stax;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="true">[email protected]</to>
|
||||
<from>[email protected]</from>
|
||||
</notification>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<notification id="5">
|
||||
<to customer="false">[email protected]</to>
|
||||
<from>[email protected]</from>
|
||||
</notification>
|
||||
@@ -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">[email protected]</to>
|
||||
<from>[email protected]</from>
|
||||
</notification>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user