org.zwobble.mammoth.internal.html.HtmlWriter 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
package org.zwobble.mammoth.internal.html;
import java.util.Map;
import static org.zwobble.mammoth.internal.util.Lists.orderedBy;
public class HtmlWriter {
public static void write(HtmlNode node, StringBuilder builder) {
node.accept(new HtmlNode.Visitor() {
@Override
public void visit(HtmlElement element) {
builder.append("<").append(element.getTagName());
HtmlWriter.generateAttributes(element.getAttributes(), builder);
builder.append(">");
element.getChildren().forEach(child -> write(child, builder));
builder
.append("")
.append(element.getTagName())
.append(">");
}
@Override
public void visit(HtmlSelfClosingElement element) {
builder.append("<").append(element.getTagName());
HtmlWriter.generateAttributes(element.getAttributes(), builder);
builder.append(" />");
}
@Override
public void visit(HtmlTextNode node) {
builder.append(HtmlWriter.escapeText(node.getValue()));
}
@Override
public void visit(HtmlForceWrite forceWrite) {
}
});
}
private static void generateAttributes(Map attributes, StringBuilder builder) {
for (Map.Entry attribute : orderedBy(attributes.entrySet(), Map.Entry::getKey)) {
builder
.append(" ")
.append(attribute.getKey())
.append("=\"")
.append(HtmlWriter.escapeAttributeValue(attribute.getValue()))
.append("\"");
}
}
private static String escapeText(String text) {
return text.replace("&", "&").replace("<", "<").replace(">", ">");
}
private static String escapeAttributeValue(String value) {
return escapeText(value).replace("\"", """);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy