// TagWriter.java
//
// by Jens Hofschröer, @nigjo
// http://blog.nigjo.de/netbeans/
//
// Licence: CC-BY, https://creativecommons.org/licenses/by/4.0/
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Helperclass to format a simple XML/HTML Tag with or without content.
*
* @author Jens Hofschröer
*/
public final class TagWriter {
private final String name;
private Map<String, String> attr;
private String rawContent;
public TagWriter(String name) {
this.name = name;
}
/**
* Add a new or replace an existing attribute of this tag.
*
* @param key attribute key
* @param value attribute string as raw text
*
* @return this tag
*/
public TagWriter setAttribute(String key, String value) {
if(this.attr == null) {
this.attr = new LinkedHashMap<>();
}
attr.put(key, value);
return this;
}
/**
* Adds some content to the existing content.
*
* @param content text content to be added. This additional text will be XML-encoded
* before adding.
*
* @return this tag
*/
public TagWriter addContent(String content) {
if(this.rawContent == null) {
this.rawContent = encode(content);
} else {
this.rawContent += encode(content);
}
return this;
}
/**
* Sets the full content for this tag.
*
* @param content new content for this tag. The text will be XML encoded.
*
* @return this tag
*/
public TagWriter setContent(String content) {
this.rawContent = encode(content);
return this;
}
/**
* sets the full raw content for this tag.
*
* @param content the content for this tag. This value will not be changed and should be
* well prepared.
*
* @return this tag
*/
public TagWriter setRawContent(String content) {
this.rawContent = content;
return this;
}
/**
* Performs a simple XML encoding to the given string. The characters {@code &},
* {@code <}, {@code >} and {@code "} will be replaced by thier XML entities. There will
* be no replacement for special HTML characters.
*
* <p>
* <strong>Attention:</strong> If there are already encoded entities in the text, the
* ampersand of these entities will be encoded again.
*
* @param raw the "raw" text.
*
* @return encoded text.
*/
public String encode(String raw) {
return raw
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """);
}
/**
* creates the formatted tag with its attributs and content. There will be no indention
* formatting for the tag.
*
* @return fully formated tag.
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append('<').append(name);
if(attr != null) {
for(Map.Entry<String, String> entry : attr.entrySet()) {
b.append(' ').append(entry.getKey())
.append("='").append(entry.getValue())
.append('\'');
}
}
if(rawContent != null) {
b.append('>')
.append(rawContent)
.append("</").append(name).append('>');
} else {
b.append(" />");
}
return b.toString();
}
}