📄 xmloutputter.java
字号:
/*--
$Id: XMLOutputter.java,v 1.116 2007/11/10 05:29:01 jhunter Exp $
Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "JDOM" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact <request_AT_jdom_DOT_org>.
4. Products derived from this software may not be called "JDOM", nor
may "JDOM" appear in their name, without prior written permission
from the JDOM Project Management <request_AT_jdom_DOT_org>.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed by the
JDOM Project (http://www.jdom.org/)."
Alternatively, the acknowledgment may be graphical using the logos
available at http://www.jdom.org/images/logos.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
This software consists of voluntary contributions made by many
individuals on behalf of the JDOM Project and was originally
created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
on the JDOM Project, please see <http://www.jdom.org/>.
*/
package org.jdom.output;
import java.io.*;
import java.util.*;
import javax.xml.transform.Result;
import org.jdom.*;
/**
* Outputs a JDOM document as a stream of bytes. The outputter can manage many
* styles of document formatting, from untouched to pretty printed. The default
* is to output the document content exactly as created, but this can be changed
* by setting a new Format object. For pretty-print output, use
* <code>{@link Format#getPrettyFormat()}</code>. For whitespace-normalized
* output, use <code>{@link Format#getCompactFormat()}</code>.
* <p>
* There are <code>{@link #output output(...)}</code> methods to print any of
* the standard JDOM classes, including Document and Element, to either a Writer
* or an OutputStream. <b>Warning</b>: When outputting to a Writer, make sure
* the writer's encoding matches the encoding setting in the Format object. This
* ensures the encoding in which the content is written (controlled by the
* Writer configuration) matches the encoding placed in the document's XML
* declaration (controlled by the XMLOutputter). Because a Writer cannot be
* queried for its encoding, the information must be passed to the Format
* manually in its constructor or via the
* <code>{@link Format#setEncoding}</code> method. The default encoding is
* UTF-8.
* <p>
* The methods <code>{@link #outputString outputString(...)}</code> are for
* convenience only; for top performance you should call one of the <code>{@link
* #output output(...)}</code> methods and pass in your own Writer or
* OutputStream if possible.
* <p>
* XML declarations are always printed on their own line followed by a line
* seperator (this doesn't change the semantics of the document). To omit
* printing of the declaration use
* <code>{@link Format#setOmitDeclaration}</code>. To omit printing of the
* encoding in the declaration use <code>{@link Format#setOmitEncoding}</code>.
* Unfortunatly there is currently no way to know the original encoding of the
* document.
* <p>
* Empty elements are by default printed as <empty/>, but this can be
* configured with <code>{@link Format#setExpandEmptyElements}</code> to cause
* them to be expanded to <empty></empty>.
*
* @version $Revision: 1.116 $, $Date: 2007/11/10 05:29:01 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Jason Reid
* @author Wolfgang Werner
* @author Elliotte Rusty Harold
* @author David & Will (from Post Tool Design)
* @author Dan Schaffer
* @author Alex Chaffee
* @author Bradley S. Huffman
*/
public class XMLOutputter implements Cloneable {
private static final String CVS_ID =
"@(#) $RCSfile: XMLOutputter.java,v $ $Revision: 1.116 $ $Date: 2007/11/10 05:29:01 $ $Name: jdom_1_1 $";
// For normal output
private Format userFormat = Format.getRawFormat();
// For xml:space="preserve"
protected static final Format preserveFormat = Format.getRawFormat();
// What's currently in use
protected Format currentFormat = userFormat;
/** Whether output escaping is enabled for the being processed
* Element - default is <code>true</code> */
private boolean escapeOutput = true;
// * * * * * * * * * * Constructors * * * * * * * * * *
// * * * * * * * * * * Constructors * * * * * * * * * *
/**
* This will create an <code>XMLOutputter</code> with the default
* {@link Format} matching {@link Format#getRawFormat}.
*/
public XMLOutputter() {
}
/**
* This will create an <code>XMLOutputter</code> with the specified
* format characteristics. Note the format object is cloned internally
* before use.
*/
public XMLOutputter(Format format) {
userFormat = (Format) format.clone();
currentFormat = userFormat;
}
/**
* This will create an <code>XMLOutputter</code> with all the
* options as set in the given <code>XMLOutputter</code>. Note
* that <code>XMLOutputter two = (XMLOutputter)one.clone();</code>
* would work equally well.
*
* @param that the XMLOutputter to clone
*/
public XMLOutputter(XMLOutputter that) {
this.userFormat = (Format) that.userFormat.clone();
currentFormat = userFormat;
}
// * * * * * * * * * * Set parameters methods * * * * * * * * * *
// * * * * * * * * * * Set parameters methods * * * * * * * * * *
/**
* Sets the new format logic for the outputter. Note the Format
* object is cloned internally before use.
*
* @param newFormat the format to use for output
*/
public void setFormat(Format newFormat) {
this.userFormat = (Format) newFormat.clone();
this.currentFormat = userFormat;
}
/**
* Returns the current format in use by the outputter. Note the
* Format object returned is a clone of the one used internally.
*/
public Format getFormat() {
return (Format) userFormat.clone();
}
// * * * * * * * * * * Output to a OutputStream * * * * * * * * * *
// * * * * * * * * * * Output to a OutputStream * * * * * * * * * *
/**
* This will print the <code>Document</code> to the given output stream.
* The characters are printed using the encoding specified in the
* constructor, or a default of UTF-8.
*
* @param doc <code>Document</code> to format.
* @param out <code>OutputStream</code> to use.
* @throws IOException - if there's any problem writing.
*/
public void output(Document doc, OutputStream out)
throws IOException {
Writer writer = makeWriter(out);
output(doc, writer); // output() flushes
}
/**
* Print out the <code>{@link DocType}</code>.
*
* @param doctype <code>DocType</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(DocType doctype, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(doctype, writer); // output() flushes
}
/**
* Print out an <code>{@link Element}</code>, including
* its <code>{@link Attribute}</code>s, and all
* contained (child) elements, etc.
*
* @param element <code>Element</code> to output.
* @param out <code>Writer</code> to use.
*/
public void output(Element element, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(element, writer); // output() flushes
}
/**
* This will handle printing out an <code>{@link
* Element}</code>'s content only, not including its tag, and
* attributes. This can be useful for printing the content of an
* element that contains HTML, like "<description>JDOM is
* <b>fun>!</description>".
*
* @param element <code>Element</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void outputElementContent(Element element, OutputStream out)
throws IOException {
Writer writer = makeWriter(out);
outputElementContent(element, writer); // output() flushes
}
/**
* This will handle printing out a list of nodes.
* This can be useful for printing the content of an element that
* contains HTML, like "<description>JDOM is
* <b>fun>!</description>".
*
* @param list <code>List</code> of nodes.
* @param out <code>OutputStream</code> to use.
*/
public void output(List list, OutputStream out)
throws IOException {
Writer writer = makeWriter(out);
output(list, writer); // output() flushes
}
/**
* Print out a <code>{@link CDATA}</code> node.
*
* @param cdata <code>CDATA</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(CDATA cdata, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(cdata, writer); // output() flushes
}
/**
* Print out a <code>{@link Text}</code> node. Perfoms
* the necessary entity escaping and whitespace stripping.
*
* @param text <code>Text</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(Text text, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(text, writer); // output() flushes
}
/**
* Print out a <code>{@link Comment}</code>.
*
* @param comment <code>Comment</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(Comment comment, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(comment, writer); // output() flushes
}
/**
* Print out a <code>{@link ProcessingInstruction}</code>.
*
* @param pi <code>ProcessingInstruction</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(ProcessingInstruction pi, OutputStream out)
throws IOException {
Writer writer = makeWriter(out);
output(pi, writer); // output() flushes
}
/**
* Print out a <code>{@link EntityRef}</code>.
*
* @param entity <code>EntityRef</code> to output.
* @param out <code>OutputStream</code> to use.
*/
public void output(EntityRef entity, OutputStream out) throws IOException {
Writer writer = makeWriter(out);
output(entity, writer); // output() flushes
}
/**
* Get an OutputStreamWriter, using prefered encoding
* (see {@link Format#setEncoding}).
*/
private Writer makeWriter(OutputStream out)
throws java.io.UnsupportedEncodingException {
return makeWriter(out, userFormat.encoding);
}
/**
* Get an OutputStreamWriter, use specified encoding.
*/
private static Writer makeWriter(OutputStream out, String enc)
throws java.io.UnsupportedEncodingException {
// "UTF-8" is not recognized before JDK 1.1.6, so we'll translate
// into "UTF8" which works with all JDKs.
if ("UTF-8".equals(enc)) {
enc = "UTF8";
}
Writer writer = new BufferedWriter(
(new OutputStreamWriter(
new BufferedOutputStream(out), enc)
));
return writer;
}
// * * * * * * * * * * Output to a Writer * * * * * * * * * *
// * * * * * * * * * * Output to a Writer * * * * * * * * * *
/**
* This will print the <code>Document</code> to the given Writer.
*
* <p>
* Warning: using your own Writer may cause the outputter's
* preferred character encoding to be ignored. If you use
* encodings other than UTF-8, we recommend using the method that
* takes an OutputStream instead.
* </p>
*
* @param doc <code>Document</code> to format.
* @param out <code>Writer</code> to use.
* @throws IOException - if there's any problem writing.
*/
public void output(Document doc, Writer out) throws IOException {
printDeclaration(out, doc, userFormat.encoding);
// Print out root element, as well as any root level
// comments and processing instructions,
// starting with no indentation
List content = doc.getContent();
int size = content.size();
for (int i = 0; i < size; i++) {
Object obj = content.get(i);
if (obj instanceof Element) {
printElement(out, doc.getRootElement(), 0,
createNamespaceStack());
}
else if (obj instanceof Comment) {
printComment(out, (Comment) obj);
}
else if (obj instanceof ProcessingInstruction) {
printProcessingInstruction(out, (ProcessingInstruction) obj);
}
else if (obj instanceof DocType) {
printDocType(out, doc.getDocType());
// Always print line separator after declaration, helps the
// output look better and is semantically inconsequential
out.write(currentFormat.lineSeparator);
}
else {
// XXX if we get here then we have a illegal content, for
// now we'll just ignore it
}
newline(out);
indent(out, 0);
}
// Output final line separator
// We output this no matter what the newline flags say
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -