⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlwriter.java

📁 基于Jabber协议的即时消息服务器
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        writer.write( ";" );        lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;    }    protected void writeComment(String text) throws IOException {        if (format.isNewlines()) {            println();            indent();        }        writer.write( "<!--" );        writer.write( text );        writer.write( "-->" );        lastOutputNodeType = Node.COMMENT_NODE;    }    /** Writes the attributes of the given element      *      */    protected void writeAttributes( Element element ) throws IOException {        // I do not yet handle the case where the same prefix maps to        // two different URIs. For attributes on the same element        // this is illegal; but as yet we don't throw an exception        // if someone tries to do this        for ( int i = 0, size = element.attributeCount(); i < size; i++ ) {            Attribute attribute = element.attribute(i);            Namespace ns = attribute.getNamespace();            if (ns != null && ns != Namespace.NO_NAMESPACE && ns != Namespace.XML_NAMESPACE) {                String prefix = ns.getPrefix();                String uri = namespaceStack.getURI(prefix);                if (!ns.getURI().equals(uri)) { // output a new namespace declaration                    writeNamespace(ns);                    namespaceStack.push(ns);                }            }            // If the attribute is a namespace declaration, check if we have already            // written that declaration elsewhere (if that's the case, it must be            // in the namespace stack            String attName = attribute.getName();            if (attName.startsWith("xmlns:")) {                String prefix = attName.substring(6);                if (namespaceStack.getNamespaceForPrefix(prefix) == null) {                    String uri = attribute.getValue();                    namespaceStack.push(prefix, uri);                    writeNamespace(prefix, uri);                }            } else if (attName.equals("xmlns")) {                if (namespaceStack.getDefaultNamespace() == null) {                    String uri = attribute.getValue();                    namespaceStack.push(null, uri);                    writeNamespace(null, uri);                }            } else {                char quote = format.getAttributeQuoteCharacter();                writer.write(" ");                writer.write(attribute.getQualifiedName());                writer.write("=");                writer.write(quote);                writeEscapeAttributeEntities(attribute.getValue());                writer.write(quote);            }        }    }    protected void writeAttribute(Attribute attribute) throws IOException {        writer.write(" ");        writer.write(attribute.getQualifiedName());        writer.write("=");        char quote = format.getAttributeQuoteCharacter();        writer.write(quote);        writeEscapeAttributeEntities(attribute.getValue());        writer.write(quote);        lastOutputNodeType = Node.ATTRIBUTE_NODE;    }    protected void writeAttributes(Attributes attributes) throws IOException {        for (int i = 0, size = attributes.getLength(); i < size; i++) {            writeAttribute( attributes, i );        }    }    protected void writeAttribute(Attributes attributes, int index) throws IOException {        char quote = format.getAttributeQuoteCharacter();        writer.write(" ");        writer.write(attributes.getQName(index));        writer.write("=");        writer.write(quote);        writeEscapeAttributeEntities(attributes.getValue(index));        writer.write(quote);    }    protected void indent() throws IOException {        String indent = format.getIndent();        if ( indent != null && indent.length() > 0 ) {            for ( int i = 0; i < indentLevel; i++ ) {                writer.write(indent);            }        }    }    /**     * <p>     * This will print a new line only if the newlines flag was set to true     * </p>     */    protected void writePrintln() throws IOException  {        if (format.isNewlines()) {            writer.write( format.getLineSeparator() );        }    }    /**     * Get an OutputStreamWriter, use preferred encoding.     */    protected Writer createWriter(OutputStream outStream, String encoding) throws UnsupportedEncodingException {        return new BufferedWriter(            new OutputStreamWriter( outStream, encoding )        );    }    /**     * <p>     * This will write the declaration to the given Writer.     *   Assumes XML version 1.0 since we don't directly know.     * </p>     */    protected void writeDeclaration() throws IOException {        String encoding = format.getEncoding();        // Only print of declaration is not suppressed        if (! format.isSuppressDeclaration()) {            // Assume 1.0 version            if (encoding.equals("UTF8")) {                writer.write("<?xml version=\"1.0\"");                if (!format.isOmitEncoding()) {                    writer.write(" encoding=\"UTF-8\"");                }                writer.write("?>");            } else {                writer.write("<?xml version=\"1.0\"");                if (! format.isOmitEncoding()) {                    writer.write(" encoding=\"" + encoding + "\"");                }                writer.write("?>");            }            if (format.isNewLineAfterDeclaration()) {                println();            }        }    }    protected void writeClose(String qualifiedName) throws IOException {        writer.write("</");        writer.write(qualifiedName);        writer.write(">");    }    protected void writeEmptyElementClose(String qualifiedName) throws IOException {        // Simply close up        if (! format.isExpandEmptyElements()) {            writer.write("/>");        } else {            writer.write("></");            writer.write(qualifiedName);            writer.write(">");        }    }    protected boolean isExpandEmptyElements() {        return format.isExpandEmptyElements();    }    /** This will take the pre-defined entities in XML 1.0 and      * convert their character representation to the appropriate      * entity reference, suitable for XML attributes.      */    protected String escapeElementEntities(String text) {        char[] block = null;        int i, last = 0, size = text.length();        for ( i = 0; i < size; i++ ) {            String entity = null;            char c = text.charAt(i);            switch( c ) {                case '<' :                    entity = "&lt;";                    break;                case '>' :                    entity = "&gt;";                    break;                case '&' :                    entity = "&amp;";                    break;                case '\t': case '\n': case '\r':                    // don't encode standard whitespace characters                    if (preserve) {                      entity=String.valueOf(c);                    }                    break;                default:                	if (c < 32 || shouldEncodeChar(c)) {                        entity = "&#" + (int) c + ";";                	}                    break;            }            if (entity != null) {                if ( block == null ) {                    block = text.toCharArray();                }                buffer.append(block, last, i - last);                buffer.append(entity);                last = i + 1;            }        }        if ( last == 0 ) {            return text;        }        if ( last < size ) {            if ( block == null ) {                block = text.toCharArray();            }            buffer.append(block, last, i - last);        }        String answer = buffer.toString();        buffer.setLength(0);        return answer;    }    protected void writeEscapeAttributeEntities(String text) throws IOException {        if ( text != null ) {            String escapedText = escapeAttributeEntities( text );            writer.write( escapedText );        }    }    /** This will take the pre-defined entities in XML 1.0 and      * convert their character representation to the appropriate      * entity reference, suitable for XML attributes.      */    protected String escapeAttributeEntities(String text) {        char quote = format.getAttributeQuoteCharacter();        char[] block = null;        int i, last = 0, size = text.length();        for ( i = 0; i < size; i++ ) {            String entity = null;            char c = text.charAt(i);            switch( c ) {                case '<' :                    entity = "&lt;";                    break;                case '>' :                    entity = "&gt;";                    break;                case '\'' :                    if (quote == '\'') {                        entity = "&apos;";                    }                    break;                case '\"' :                    if (quote == '\"') {                        entity = "&quot;";                    }                    break;                case '&' :                    entity = "&amp;";                    break;                case '\t': case '\n': case '\r':                    // don't encode standard whitespace characters                    break;                default:                	if (c < 32 || shouldEncodeChar(c)) {                        entity = "&#" + (int) c + ";";                	}                    break;            }            if (entity != null) {                if ( block == null ) {                    block = text.toCharArray();                }                buffer.append(block, last, i - last);                buffer.append(entity);                last = i + 1;            }        }        if ( last == 0 ) {            return text;        }        if ( last < size ) {            if ( block == null ) {                block = text.toCharArray();            }            buffer.append(block, last, i - last);        }        String answer = buffer.toString();        buffer.setLength(0);        return answer;    }	/**	 * Should the given character be escaped. This depends on the	 * encoding of the document.	 *	 * @return boolean	 */	protected boolean shouldEncodeChar(char c) {		int max = getMaximumAllowedCharacter();		return max > 0 && c > max;	}	/**	 * Returns the maximum allowed character code that should be allowed	 * unescaped which defaults to 127 in US-ASCII (7 bit) or	 * 255 in ISO-* (8 bit).	 */	protected int defaultMaximumAllowedCharacter() {		String encoding = format.getEncoding();		if (encoding != null) {			if (encoding.equals("US-ASCII")) {				return 127;			}		}		// no encoding for things like ISO-*, UTF-8 or UTF-16		return -1;	}    protected boolean isNamespaceDeclaration( Namespace ns ) {        if (ns != null && ns != Namespace.XML_NAMESPACE) {            String uri = ns.getURI();            if ( uri != null ) {                if ( ! namespaceStack.contains( ns ) ) {                    return true;                }            }        }        return false;    }    protected void handleException(IOException e) throws SAXException {        throw new SAXException(e);    }    //Laramie Crocker 4/8/2002 10:38AM    /** Lets subclasses get at the current format object, so they can call setTrimText, setNewLines, etc.      * Put in to support the HTMLWriter, in the way      *  that it pushes the current newline/trim state onto a stack and overrides      *  the state within preformatted tags.      */    protected OutputFormat getOutputFormat() {        return format;    }    public boolean resolveEntityRefs() {        return resolveEntityRefs;    }    public void setResolveEntityRefs(boolean resolve) {        this.resolveEntityRefs = resolve;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -