Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BAEL-2338 #6150

Merged
merged 10 commits into from
Mar 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions xml/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
- [XML Libraries Support in Java](http://www.baeldung.com/java-xml-libraries)
- [DOM parsing with Xerces](http://www.baeldung.com/java-xerces-dom-parsing)
- [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file)
- [Convert XML to HTML](https://www.baeldung.com/)
16 changes: 16 additions & 0 deletions xml/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@
<version>${jdom2.version}</version>
</dependency>

<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxp-api</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>javax.xml.stream</groupId>
<artifactId>stax-api</artifactId>
<version>1.0-2</version>
</dependency>

<!-- utils -->
<dependency>
<groupId>commons-io</groupId>
Expand Down
10 changes: 10 additions & 0 deletions xml/src/main/java/com/baeldung/xmlhtml/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.baeldung.xmlhtml;

import com.baeldung.xmlhtml.helpers.XMLRunner;

public class Application {

public static void main(String[] args) {
XMLRunner.doWork();
}
}
22 changes: 22 additions & 0 deletions xml/src/main/java/com/baeldung/xmlhtml/Constants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.baeldung.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";
}
16 changes: 16 additions & 0 deletions xml/src/main/java/com/baeldung/xmlhtml/helpers/XMLRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.baeldung.xmlhtml.helpers;


import com.baeldung.xmlhtml.helpers.jaxb.JAXBHelper;
import com.baeldung.xmlhtml.helpers.jaxp.JAXPHelper;
import com.baeldung.xmlhtml.helpers.stax.STAXHelper;

public class XMLRunner {

public static void doWork() {
JAXBHelper.example();
JAXPHelper.saxParser();
JAXPHelper.documentBuilder();
STAXHelper.write(STAXHelper.read());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.baeldung.xmlhtml.helpers.jaxb;

import com.baeldung.xmlhtml.pojo.jaxb.html.ExampleHTML;
import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Body;
import com.baeldung.xmlhtml.pojo.jaxb.html.elements.CustomElement;
import com.baeldung.xmlhtml.pojo.jaxb.html.elements.Meta;
import com.baeldung.xmlhtml.pojo.jaxb.html.elements.NestedElement;
import com.baeldung.xmlhtml.pojo.jaxb.xml.XMLExample;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import java.io.File;

import static com.baeldung.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);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.baeldung.xmlhtml.helpers.jaxp;

import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;

import static com.baeldung.xmlhtml.Constants.*;

public class CustomHandler implements ContentHandler {

public void startDocument() {}

public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) { }

public void endDocument() {
System.out.println(DOCUMENT_END);
}

public void endElement(String uri, String localName, String qName) { }

public void startPrefixMapping(String prefix, String uri) { }

public void endPrefixMapping(String prefix) { }

public void setDocumentLocator(Locator locator) { }

public void characters(char[] ch, int start, int length) { }

public void ignorableWhitespace(char[] ch, int start, int length) { }

public void processingInstruction(String target, String data) { }

public void skippedEntity(String name) { }

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.baeldung.xmlhtml.helpers.jaxp;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.XMLReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

import static com.baeldung.xmlhtml.Constants.*;

public class JAXPHelper {

private static void print(Document document) {
NodeList list = document.getChildNodes();
try {
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
String message =
node.getNodeType()
+ WHITE_SPACE
+ node.getNodeName()
+ LINE_BREAK;
System.out.println(message);
}
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
}

public static void saxParser() {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
try {
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new CustomHandler());
xmlReader.parse(XML_FILE_IN);
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
}

public static void documentBuilder() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document parsed = db.parse(new File(XML_FILE_IN));
Element xml = parsed.getDocumentElement();

Document doc = db.newDocument();
Element html = doc.createElement("html");
Element head = doc.createElement("head");
html.appendChild(head);

Element body = doc.createElement("body");
Element descendantOne = doc.createElement("p");
descendantOne.setTextContent("descendantOne: " +
xml.getElementsByTagName("descendantOne")
.item(0).getTextContent());
Element descendantThree = doc.createElement("p");
descendantThree.setTextContent("descendantThree: " +
xml.getElementsByTagName("descendantThree")
.item(0).getTextContent());
Element nested = doc.createElement("div");
nested.appendChild(descendantThree);

body.appendChild(descendantOne);
body.appendChild(nested);
html.appendChild(body);
doc.appendChild(html);

TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory
.newTransformer()
.transform(new DOMSource(doc), new StreamResult(new File(JAXP_FILE_OUT)));

} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
}
}
112 changes: 112 additions & 0 deletions xml/src/main/java/com/baeldung/xmlhtml/helpers/stax/STAXHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.baeldung.xmlhtml.helpers.stax;

import com.baeldung.xmlhtml.pojo.stax.Body;
import com.baeldung.xmlhtml.pojo.stax.CustomElement;
import com.baeldung.xmlhtml.pojo.stax.NestedElement;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import java.io.FileInputStream;
import java.io.FileWriter;

import static com.baeldung.xmlhtml.Constants.*;

public class STAXHelper {

private static XMLStreamReader reader() {
XMLStreamReader xmlStreamReader = null;
try {
xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(XML_FILE_IN));
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return xmlStreamReader;
}

private static XMLStreamWriter writer() {
XMLStreamWriter xmlStreamWriter = null;
try {
xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(STAX_FILE_OUT));
} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return xmlStreamWriter;
}

public static Body read() {
Body body = new Body();
try {
XMLStreamReader xmlStreamReader = reader();

CustomElement customElement = new CustomElement();
NestedElement nestedElement = new NestedElement();
CustomElement child = new CustomElement();

while (xmlStreamReader.hasNext()) {
xmlStreamReader.next();
if (xmlStreamReader.isStartElement()) {
System.out.println(xmlStreamReader.getLocalName());
if (xmlStreamReader.getLocalName().equals("descendantOne")) {
customElement.setValue(xmlStreamReader.getElementText());
}
if (xmlStreamReader.getLocalName().equals("descendantThree")) {
child.setValue(xmlStreamReader.getElementText());
}
}
}

nestedElement.setCustomElement(child);
body.setCustomElement(customElement);
body.setNestedElement(nestedElement);

xmlStreamReader.close();

} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}
return body;
}

public static void write(Body body) {
try {

XMLStreamWriter xmlStreamWriter = writer();
xmlStreamWriter.writeStartElement("html");
xmlStreamWriter.writeCharacters(BREAK + TAB);
xmlStreamWriter.writeStartElement("head");
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB);
xmlStreamWriter.writeStartElement("meta");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK + TAB);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK + TAB);
xmlStreamWriter.writeStartElement("body");
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB);
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters("descendantOne: " + body.getCustomElement().getValue());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB);
xmlStreamWriter.writeStartElement("div");
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB);
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters(BREAK);
xmlStreamWriter.writeCharacters(TAB + TAB + TAB + TAB + "descendantThree: " + body.getNestedElement().getCustomElement().getValue());
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB + TAB);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK + TAB + TAB);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK + TAB);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeCharacters(BREAK);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.flush();
xmlStreamWriter.close();

} catch (Exception ex) {
System.out.println(EXCEPTION_ENCOUNTERED + ex);
}

}
}
Loading