Java Getriebe

Java und NetBeans

Simple XML/HTML Tag Writer

Eine einfache „Builder“-Klasse, mit der sich vergleichsweise leicht XML/HTML Tags erstellen lassen. Ich brauche die Klasse immer mal wieder, wenn ich einzelne HTML-Ausgaben erstellen muss (hier aus einem „@todo„-Taglet)

1
2
3
4
5
6
7
8
9
10
11
    String dt = new TagWriter("dt")
        .setAttribute("class", "simpleTagLabel")
        .setRawContent(new TagWriter("span")
            .setAttribute("style", "background-color:orange;padding:.5em;")
            .setContent("Zu Erledigen:")
            .toString())
        .toString();
    String dd = new TagWriter("dd")
        .setContent(tag.text())
        .toString();
    return dt + dd;

Die Klasse kommt auch mit „leeren“ Tag zurecht und schließt diese korrekt.

So lange ich als Autor genannt werde, kann die Klasse in jeglicher Art von Projekten verwendet werden

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// 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("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace(""", "&quot;");
  }

  /**
   * 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();
  }
}

Creative Commons Lizenzvertrag
Dieses Werk ist lizenziert unter einer Creative Commons Namensnennung 4.0 International Lizenz.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.