
org.zwobble.mammoth.internal.xml.XmlWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mammoth Show documentation
Show all versions of mammoth Show documentation
Convert Word documents to simple and clean HTML
The newest version!
package org.zwobble.mammoth.internal.xml;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class XmlWriter {
public static String toString(XmlElement element, NamespacePrefixes namespaces) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XmlWriter writer = new XmlWriter(createXmlWriter(outputStream), namespaces);
writer.writeDocument(element);
return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
} catch (XMLStreamException exception) {
throw new RuntimeException(exception);
}
}
private static XMLStreamWriter createXmlWriter(ByteArrayOutputStream outputStream) throws XMLStreamException {
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
return outputFactory.createXMLStreamWriter(outputStream, "UTF-8");
}
private final XMLStreamWriter writer;
private final NamespacePrefixes namespaces;
private XmlWriter(XMLStreamWriter writer, NamespacePrefixes namespaces) {
this.writer = writer;
this.namespaces = namespaces;
}
private void writeDocument(XmlElement element) throws XMLStreamException {
writer.writeStartDocument("UTF-8", "1.0");
writeStartElement(element);
writeNamespaces(namespaces);
writeAttributes(element);
writeNodes(element.getChildren());
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeNodes(List children) {
for (XmlNode child : children) {
writeNode(child);
}
}
private void writeNode(XmlNode child) {
child.accept(new XmlNodeVisitor
© 2015 - 2025 Weber Informatics LLC | Privacy Policy