Top Description Inners Fields Constructors Methods
org.dom4j.io

public Class HTMLWriter

extends XMLWriter
Class Inheritance
Imports
java.io.IOException, .OutputStream, .StringWriter, .UnsupportedEncodingException, .Writer, java.util.HashSet, .Iterator, .Set, .Stack, org.dom4j.Document, .DocumentHelper, .Element, .Entity, .Node, org.xml.sax.SAXException

HTMLWriter takes a DOM4J tree and formats it to a stream as HTML. This formatter is similar to XMLWriter but it outputs the text of CDATA and Entity sections rather than the serialised format as in XML, it has an XHTML mode, it retains whitespace in certain elements such as <PRE>, and it supports certain elements which have no corresponding close tag such as for <BR> and <P>. The OutputFormat passed in to the constructor is checked for isXHTML() and isExpandEmptyElements(). See OutputFormatfor details. Here are the rules for this class based on an OutputFormat, "format", passed in to the constructor: Examples If isXHTML == true, CDATA sections look like this:
<myelement><![CDATA[My data]]></myelement> 
Otherwise, they look like this:
<myelement>My data</myelement> 
Basically, OutputFormat#isXHTML() == true will produce valid XML, while OutputFormat#isExpandEmptyElements() determines whether empty elements are expanded if isXHTML is true, excepting the special HTML single tags. Also, HTMLWriter handles tags whose contents should be preformatted, that is, whitespace-preserved. By default, this set includes the tags <PRE>, <SCRIPT>, <STYLE>, and <TEXTAREA>, case insensitively. It does not include <IFRAME>. Other tags, such as <CODE>, <KBD>, <TT>, <VAR>, are usually rendered in a different font in most browsers, but don't preserve whitespace, so they also don't appear in the default list. HTML Comments are always whitespace-preserved. However, the parser you use may store comments with linefeed-only text nodes (\n) even if your platform uses another line.separator character, and HTMLWriter outputs Comment nodes exactly as the DOM is set up by the parser. See examples and discussion here: setPreformattedTags(java.util.Set) Examples Pretty Printing This example shows how to pretty print a string containing a valid HTML document to a string. You can also just call the static methods of this class: prettyPrintHTML(String)or prettyPrintHTML(String, boolean, boolean, boolean, boolean) or prettyPrintXHTML(String) for XHTML (note the X)
String testPrettyPrint(String html) {
    StringWriter sw = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    // These are the default values for createPrettyPrint,
    // so you needn't set them:
    // format.setNewlines(true);
    // format.setTrimText(true);</font>
    format.setXHTML(true);
    HTMLWriter writer = new HTMLWriter(sw, format);
    Document document = DocumentHelper.parseText(html);
    writer.write(document);
    writer.flush();
    return sw.toString();
}
This example shows how to create a "squeezed" document, but one that will work in browsers even if the browser line length is limited. No newlines are included, no extra whitespace at all, except where it it required by setPreformattedTags.
String testCrunch(String html) {
    StringWriter sw = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewlines(false);
    format.setTrimText(true);
    format.setIndent("");
    format.setXHTML(true);
    format.setExpandEmptyElements(false);
    format.setNewLineAfterNTags(20);
    org.dom4j.io.HTMLWriter writer = new HTMLWriter(sw, format);
    org.dom4j.Document document = DocumentHelper.parseText(html);
    writer.write(document);
    writer.flush();
    return sw.toString();
}
Authors
James Strachan , Laramie Crocker
Version
$Revision: 1.21 $

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class

Field Summary

Modifier and TypeField and Description
protected static final OutputFormat
protected static final HashSet<String>
private Stack<HTMLWriter.FormatState>
private String
private static String
private int
private HashSet<String>
omitElementCloseSet

Used to store the qualified element names which should have no close element tag

private HashSet<String>
private int
Inherited from org.dom4j.io.XMLWriter:
DEFAULT_FORMATlastOutputNodeTypeLEXICAL_HANDLER_NAMESpreservewriter

Constructor Summary

AccessConstructor and Description
public
public
HTMLWriter(Writer writer, OutputFormat format)

public
public
public
public

Method Summary

Modifier and TypeMethod and Description
public void
endCDATA()

Overrides org.dom4j.io.XMLWriter.endCDATA.

Implements org.xml.sax.ext.LexicalHandler.endCDATA.

Report the end of a CDATA section.
public Set<String>

Returns:

A clone of the Set.
getOmitElementCloseSet
()

A clone of the Set of elements that can have their close-tags omitted.

public Set<String>

Returns:

DOCUMENT ME!
getPreformattedTags
()

private HashSet<String>
public boolean

Returns:

true if the qualifiedName passed in matched (case-insensitively) a tag in the preformattedTags set, or false if not found or if the set is empty or null.
isPreformattedTag
(String
DOCUMENT ME!
qualifiedName
)

DOCUMENT ME!

private String
private void
protected void
protected boolean
omitElementClose(String qualifiedName)

public static String

Returns:

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, and leaving the close tags off of the default omitElementCloseSet set. Use one of the write methods if you want stream output.
prettyPrintHTML
(String
DOCUMENT ME!
html
)

Convenience method to just get a String result.

public static String

Returns:

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, and leaving the close tags off of the default omitElementCloseSet set. This override allows you to specify various formatter options. Use one of the write methods if you want stream output.
prettyPrintHTML
(String
DOCUMENT ME!
html
,
boolean
DOCUMENT ME!
newlines
,
boolean
DOCUMENT ME!
trim
,
boolean
DOCUMENT ME!
isXHTML
,
boolean
DOCUMENT ME!
expandEmpty
)

DOCUMENT ME!

public static String

Returns:

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, but conforming to XHTML: no close tags are omitted (though if empty, they will be converted to XHTML empty tags: <HR/> Use one of the write methods if you want stream output.
prettyPrintXHTML
(String
DOCUMENT ME!
html
)

Convenience method to just get a String result, but As XHTML .

public void
setOmitElementCloseSet(Set<String>
DOCUMENT ME!
newSet
)

To use the empty set, pass an empty Set, or null:



      setOmitElementCloseSet(new HashSet());
    or
      setOmitElementCloseSet(null);


public void
setPreformattedTags(Set<String>
DOCUMENT ME!
newSet
)

Override the default set, which includes PRE, SCRIPT, STYLE, and TEXTAREA, case insensitively.

public void
startCDATA()

Overrides org.dom4j.io.XMLWriter.startCDATA.

Implements org.xml.sax.ext.LexicalHandler.startCDATA.

Report the start of a CDATA section.
protected void
protected void
writeClose(String
DOCUMENT ME!
qualifiedName
)

Overrides org.dom4j.io.XMLWriter.writeClose.

Overriden method to not close certain element names to avoid wierd behaviour from browsers for versions up to 5.x
protected void
writeDeclaration()

Overrides org.dom4j.io.XMLWriter.writeDeclaration.

This will write the declaration to the given Writer.

protected void
writeElement(Element
DOCUMENT ME!
element
)

Overrides org.dom4j.io.XMLWriter.writeElement.

This override handles any elements that should not remove whitespace, such as <PRE>, <SCRIPT>, <STYLE>, and <TEXTAREA>.
protected void
protected void
protected void
Inherited from org.dom4j.io.XMLWriter:
charactersclosecommentcreateWriterdefaultMaximumAllowedCharacterendDocumentendDTDendElementendEntityendPrefixMappingescapeAttributeEntitiesescapeElementEntitiesflushgetLexicalHandlergetMaximumAllowedCharactergetOutputFormatgetPropertyhandleExceptionignorableWhitespaceindentinstallLexicalHandlerisElementSpacePreservedisEscapeTextisExpandEmptyElementsisNamespaceDeclarationnotationDeclparseprintlnprocessingInstructionresolveEntityRefssetDocumentLocatorsetEscapeTextsetIndentLevelsetLexicalHandlersetMaximumAllowedCharactersetOutputStreamsetPropertysetResolveEntityRefssetWritershouldEncodeCharstartDocumentstartDTDstartElementstartEntitystartPrefixMappingunparsedEntityDeclwritewritewritewritewritewritewritewritewritewritewritewritewritewriteAttributewriteAttributewriteAttributewriteAttributeswriteAttributeswriteClosewriteCommentwriteDocTypewriteDocTypewriteElementContentwriteEntityRefwriteEscapeAttributeEntitieswriteNamespacewriteNamespacewriteNamespaceswriteNamespaceswriteNodewriteNodeTextwriteOpenwritePrintlnwriteProcessingInstruction

Field Detail

DEFAULT_HTML_FORMATback to summary
protected static final OutputFormat DEFAULT_HTML_FORMAT
DEFAULT_PREFORMATTED_TAGSback to summary
protected static final HashSet<String> DEFAULT_PREFORMATTED_TAGS
formatStackback to summary
private Stack<HTMLWriter.FormatState> formatStack
lastTextback to summary
private String lastText
lineSeparatorback to summary
private static String lineSeparator
newLineAfterNTagsback to summary
private int newLineAfterNTags
omitElementCloseSetback to summary
private HashSet<String> omitElementCloseSet

Used to store the qualified element names which should have no close element tag

preformattedTagsback to summary
private HashSet<String> preformattedTags
tagsOuputback to summary
private int tagsOuput

Constructor Detail

HTMLWriterback to summary
public HTMLWriter(Writer writer)
HTMLWriterback to summary
public HTMLWriter(Writer writer, OutputFormat format)
HTMLWriterback to summary
public HTMLWriter() throws UnsupportedEncodingException
HTMLWriterback to summary
public HTMLWriter(OutputFormat format) throws UnsupportedEncodingException
HTMLWriterback to summary
public HTMLWriter(OutputStream out) throws UnsupportedEncodingException
HTMLWriterback to summary
public HTMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException

Method Detail

endCDATAback to summary
public void endCDATA() throws SAXException

Overrides org.dom4j.io.XMLWriter.endCDATA.

Implements org.xml.sax.ext.LexicalHandler.endCDATA.

Doc from org.xml.sax.ext.LexicalHandler.endCDATA.

Report the end of a CDATA section.

Exceptions
SAXException:
The application may raise an exception.
getOmitElementCloseSetback to summary
public Set<String> getOmitElementCloseSet()

A clone of the Set of elements that can have their close-tags omitted. By default it should be "AREA", "BASE", "BR", "COL", "HR", "IMG", "INPUT", "LINK", "META", "P", "PARAM"

Returns:Set<String>

A clone of the Set.

getPreformattedTagsback to summary
public Set<String> getPreformattedTags()
Returns:Set<String>

DOCUMENT ME!

See Also
setPreformattedTags
internalGetOmitElementCloseSetback to summary
private HashSet<String> internalGetOmitElementCloseSet()
isPreformattedTagback to summary
public boolean isPreformattedTag(String qualifiedName)

DOCUMENT ME!

Parameters
qualifiedName:String

DOCUMENT ME!

Returns:boolean

true if the qualifiedName passed in matched (case-insensitively) a tag in the preformattedTags set, or false if not found or if the set is empty or null.

See Also
setPreformattedTags
justSpacesback to summary
private String justSpaces(String text)
lazyInitNewLinesAfterNTagsback to summary
private void lazyInitNewLinesAfterNTags()
loadOmitElementCloseSetback to summary
protected void loadOmitElementCloseSet(Set<String> set)
omitElementCloseback to summary
protected boolean omitElementClose(String qualifiedName)
prettyPrintHTMLback to summary
public static String prettyPrintHTML(String html) throws IOException, UnsupportedEncodingException, DocumentException

Convenience method to just get a String result.

Parameters
html:String

DOCUMENT ME!

Returns:String

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, and leaving the close tags off of the default omitElementCloseSet set. Use one of the write methods if you want stream output.

Exceptions
IOException:
DOCUMENT ME!
UnsupportedEncodingException:
DOCUMENT ME!
DocumentException:
DOCUMENT ME!
prettyPrintHTMLback to summary
public static String prettyPrintHTML(String html, boolean newlines, boolean trim, boolean isXHTML, boolean expandEmpty) throws IOException, UnsupportedEncodingException, DocumentException

DOCUMENT ME!

Parameters
html:String

DOCUMENT ME!

newlines:boolean

DOCUMENT ME!

trim:boolean

DOCUMENT ME!

isXHTML:boolean

DOCUMENT ME!

expandEmpty:boolean

DOCUMENT ME!

Returns:String

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, and leaving the close tags off of the default omitElementCloseSet set. This override allows you to specify various formatter options. Use one of the write methods if you want stream output.

Exceptions
IOException:
DOCUMENT ME!
UnsupportedEncodingException:
DOCUMENT ME!
DocumentException:
DOCUMENT ME!
prettyPrintXHTMLback to summary
public static String prettyPrintXHTML(String html) throws IOException, UnsupportedEncodingException, DocumentException

Convenience method to just get a String result, but As XHTML .

Parameters
html:String

DOCUMENT ME!

Returns:String

a pretty printed String from the source string, preserving whitespace in the defaultPreformattedTags set, but conforming to XHTML: no close tags are omitted (though if empty, they will be converted to XHTML empty tags: <HR/> Use one of the write methods if you want stream output.

Exceptions
IOException:
DOCUMENT ME!
UnsupportedEncodingException:
DOCUMENT ME!
DocumentException:
DOCUMENT ME!
setOmitElementCloseSetback to summary
public void setOmitElementCloseSet(Set<String> newSet)

To use the empty set, pass an empty Set, or null:



      setOmitElementCloseSet(new HashSet());
    or
      setOmitElementCloseSet(null);


Parameters
newSet:Set<String>

DOCUMENT ME!

setPreformattedTagsback to summary
public void setPreformattedTags(Set<String> newSet)

Override the default set, which includes PRE, SCRIPT, STYLE, and TEXTAREA, case insensitively. Setting Preformatted Tags Pass in a Set of Strings, one for each tag name that should be treated like a PRE tag. You may pass in null or an empty Set to assign the empty set, in which case no tags will be treated as preformatted, except that HTML Comments will continue to be preformatted. If a tag is included in the set of preformatted tags, all whitespace within the tag will be preserved, including whitespace on the same line preceding the close tag. This will generally make the close tag not line up with the start tag, but it preserves the intention of the whitespace within the tag. The browser considers leading whitespace before the close tag to be significant, but leading whitespace before the open tag to be insignificant. For example, if the HTML author doesn't put the close TEXTAREA tag flush to the left margin, then the TEXTAREA control in the browser will have spaces on the last line inside the control. This may be the HTML author's intent. Similarly, in a PRE, the browser treats a flushed left close PRE tag as different from a close tag with leading whitespace. Again, this must be left up to the HTML author. Examples Here is an example of how you can set the PreformattedTags list using setPreformattedTags to include IFRAME, as well as the default set, if you have an instance of this class named myHTMLWriter:

Set current = myHTMLWriter.getPreformattedTags();
current.add("IFRAME");
myHTMLWriter.setPreformattedTags(current);

//The set is now <b>PRE, SCRIPT, STYLE, TEXTAREA, IFRAME</b>


Similarly, you can simply replace it with your own:


      HashSet newset = new HashSet();
      newset.add("PRE");
      newset.add("TEXTAREA");
      myHTMLWriter.setPreformattedTags(newset);

      //The set is now <b>{PRE, TEXTAREA}</b>


You can remove all tags from the preformatted tags list, with an empty set, like this:


      myHTMLWriter.setPreformattedTags(new HashSet());

      //The set is now <b>{}</b>


or with null, like this:


      myHTMLWriter.setPreformattedTags(null);

      //The set is now <b>{}</b>


Parameters
newSet:Set<String>

DOCUMENT ME!

startCDATAback to summary
public void startCDATA() throws SAXException

Overrides org.dom4j.io.XMLWriter.startCDATA.

Implements org.xml.sax.ext.LexicalHandler.startCDATA.

Doc from org.xml.sax.ext.LexicalHandler.startCDATA.

Report the start of a CDATA section.

The contents of the CDATA section will be reported through the regular characters event; this event is intended only to report the boundary.

Exceptions
SAXException:
The application may raise an exception.
writeCDATAback to summary
protected void writeCDATA(String text) throws IOException

Overrides org.dom4j.io.XMLWriter.writeCDATA.

writeCloseback to summary
protected void writeClose(String qualifiedName) throws IOException

Overrides org.dom4j.io.XMLWriter.writeClose.

Overriden method to not close certain element names to avoid wierd behaviour from browsers for versions up to 5.x

Parameters
qualifiedName:String

DOCUMENT ME!

Exceptions
IOException:
DOCUMENT ME!
writeDeclarationback to summary
protected void writeDeclaration() throws IOException

Overrides org.dom4j.io.XMLWriter.writeDeclaration.

Doc from org.dom4j.io.XMLWriter.writeDeclaration.

This will write the declaration to the given Writer. Assumes XML version 1.0 since we don't directly know.

Exceptions
IOException:
DOCUMENT ME!
writeElementback to summary
protected void writeElement(Element element) throws IOException

Overrides org.dom4j.io.XMLWriter.writeElement.

This override handles any elements that should not remove whitespace, such as <PRE>, <SCRIPT>, <STYLE>, and <TEXTAREA>.

Note

the close tags won't line up with the open tag, but we can't alter that. See javadoc note at setPreformattedTags.

Parameters
element:Element

DOCUMENT ME!

Exceptions
IOException:
When the stream could not be written to.
See Also
setPreformattedTags
writeEmptyElementCloseback to summary
protected void writeEmptyElementClose(String qualifiedName) throws IOException

Overrides org.dom4j.io.XMLWriter.writeEmptyElementClose.

writeEntityback to summary
protected void writeEntity(Entity entity) throws IOException

Overrides org.dom4j.io.XMLWriter.writeEntity.

writeStringback to summary
protected void writeString(String text) throws IOException

Overrides org.dom4j.io.XMLWriter.writeString.

org.dom4j.io back to summary

private Class HTMLWriter.FormatState

extends Object
Class Inheritance

Field Summary

Modifier and TypeField and Description
private String
private boolean
private boolean

Constructor Summary

AccessConstructor and Description
public
FormatState(boolean newLines, boolean trimText, String indent)

Method Summary

Modifier and TypeMethod and Description
public String
public boolean
public boolean
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

indentback to summary
private String indent
newlinesback to summary
private boolean newlines
trimTextback to summary
private boolean trimText

Constructor Detail

FormatStateback to summary
public FormatState(boolean newLines, boolean trimText, String indent)

Method Detail

getIndentback to summary
public String getIndent()
isNewlinesback to summary
public boolean isNewlines()
isTrimTextback to summary
public boolean isTrimText()