The Element Construction Set allows you to use Java
Objects to generate markup code. Gone is the need for writing code that looks
like the following:
|
|
|
|
out.println("<HTML>");
out.println("<HEAD><TITLE>Demo<TITLE><HEAD>");
out.println("<BODY>");
out.println("<H1>Demo Header<H1>");
out.println("<H3>Sub Header:<H3>");
out.println("<FONT SIZE=\"+1\" FACE=\"Times\" COLOR=\"#FFFFFF">);
out.println("The big dog & the little cat chased each other.");
out.println("<FONT>");
out.println("<BODY>");
out.println("<HTML>");
|
|
|
|
|
You can do this instead:
|
|
|
|
Html html = new Html()
.addElement(new Head()
.addElement(new Title("Demo")))
.addElement(new Body()
.addElement(new H1("Demo Header"))
.addElement(new H3("Sub Header:"))
.addElement(new Font().setSize("+1")
.setColor(HtmlColor.WHITE)
.setFace("Times")
.addElement("The big dog & the little cat chased each other.")));
out.println(html.toString());
// or write to the outputstream directly
output(out);
|
|
|
|
|
This creates the HTML:
|
|
|
|
<html><head><title>Demo</title></head><body><h1>Demo Header</h1><h3>Sub Header:</h3>
<font size="+1" color="#FFFFFF" face="Times">The big dog & the little cat chased
each other.</font></body></html>
|
|
|
|
|
Or even easier, use the Document object:
|
|
|
|
Document doc = (Document) new Document()
.appendTitle("Demo")
.appendBody(new H1("Demo Header"))
.appendBody(new H3("Sub Header:"))
.appendBody(new Font().setSize("+1")
.setColor(HtmlColor.WHITE)
.setFace("Times")
.addElement("The big dog & the little cat chased each other."));
out.println(doc.toString());
// or write to the outputstream directly
output(out);
|
|
|
|
|
This creates the same HTML as above.
There are some subtleties in the above code that are worth commenting on.
- You don't need to know the Hex value of the color you want. HtmlColor is an
interface that defines more than 200 colors.
- You don't need to replace & ' " with their entity counterparts, it is
done for you (this is configurable of course). ECS gives you the
ability to define filters that are applied to the element when you call
the addElement() methods.
- You can write directly to an elements output stream. output() is a
method that can be overridden to provide custom rendering of elements.
ECS also gives you the ability to create your own elements on the fly
using the XML element. So you can do the following:
|
|
|
|
XML my_element = new XML("my_element");
produces:
<my_element></my_element>
|
|
|
|
|