Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2008 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package groovy.xml;
 
 
 import java.io.Writer;
 import java.util.Map;

A helper class for creating XML or HTML markup

Author(s):
James Strachan
Stefan Matthias Aust
Scott Stirling
Paul King
Version:
$Revision: 14219 $
 
 public class MarkupBuilder extends BuilderSupport {
     private IndentPrinter out;
     private boolean nospace;
     private int state;
     private boolean nodeIsEmpty = true;
     private boolean useDoubleQuotes = false;
     private boolean omitNullAttributes = false;
     private boolean omitEmptyAttributes = false;
 
     public MarkupBuilder() {
         this(new IndentPrinter());
     }
 
     public MarkupBuilder(PrintWriter writer) {
         this(new IndentPrinter(writer));
     }
 
     public MarkupBuilder(Writer writer) {
         this(new IndentPrinter(new PrintWriter(writer)));
     }
 
     public MarkupBuilder(IndentPrinter out) {
         this. = out;
     }

    
Returns true if attribute values are output with double quotes; false if single quotes are used. By default, single quotes are used.

Returns:
true if double quotes are used for attributes
 
     public boolean getDoubleQuotes() {
         return this.;
     }

    
Sets whether the builder outputs attribute values in double quotes or single quotes.

Parameters:
useDoubleQuotes If this parameter is true, double quotes are used; otherwise, single quotes are.
 
     public void setDoubleQuotes(boolean useDoubleQuotes) {
         this. = useDoubleQuotes;
     }

    
Determine whether null attributes will appear in the produced markup.

Returns:
true, if null attributes will be removed from the resulting markup.
 
     public boolean isOmitNullAttributes() {
         return ;
     }

    
Allows null attributes to be removed the produced markup.

Parameters:
omitNullAttributes if true, null attributes will not be included in the resulting markup. If false null attributes will be included in the markup as empty strings regardless of the omitEmptyAttribute setting. Defaults to false.
 
     public void setOmitNullAttributes(boolean omitNullAttributes) {
        this. = omitNullAttributes;
    }

    
Determine whether empty attributes will appear in the produced markup.

Returns:
true, if empty attributes will be removed from the resulting markup.
    public boolean isOmitEmptyAttributes() {
        return ;
    }

    
Allows empty attributes to be removed the produced markup.

Parameters:
omitEmptyAttributes if true, empty attributes will not be included in the resulting markup. Defaults to false.
    public void setOmitEmptyAttributes(boolean omitEmptyAttributes) {
        this. = omitEmptyAttributes;
    }
    protected IndentPrinter getPrinter() {
        return this.;
    }
    protected void setParent(Object parentObject child) { }
    public Object getMkp() {
        return this;
    }
    public void yield(String value) {
        yield(valuetrue);
    }
    public void yieldUnescaped(String value) {
        yield(valuefalse);
    }
    private void yield(String valueboolean escaping) {
        if ( == 1) {
             = 2;
            this. = false;
            .print(">");
        }
        if ( == 2 ||  == 3) {
            .print(escaping ? escapeElementContent(value) : value);
        }
    }
    protected Object createNode(Object name) {
        Object theName = getName(name);
        toState(1, theName);
        this. = true;
        return theName;
    }
    protected Object createNode(Object nameObject value) {
        Object theName = getName(name);
        if (value == null){
            return createNode(theName);
        } else {
            toState(2, theName);
            this. = false;
            .print(">");
            .print(escapeElementContent(value.toString()));
            return theName;
        }
    }
    protected Object createNode(Object nameMap attributesObject value) {
        Object theName = getName(name);
        toState(1, theName);
        for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entryiter.next();
            Object attributeValue = entry.getValue();
            boolean skipNull = attributeValue == null && ;
            boolean skipEmpty = attributeValue != null &&  &&
                    attributeValue.toString().length() == 0;
            if (!skipNull && !skipEmpty) {
                .print(" ");
                // Output the attribute name,
                print(entry.getKey().toString());
                // Output the attribute value within quotes. Use whichever
                // type of quotes are currently configured.
                .print(this. ? "=\"" : "='");
                print(attributeValue == null ? "" : escapeAttributeValue(attributeValue.toString()));
                .print(this. ? "\"" : "'");
            }
        }
        if (value != null) {
            yield(value.toString());
        } else {
             = true;
        }
        return theName;
    }
    protected Object createNode(Object nameMap attributes) {
        return createNode(nameattributesnull);
    }
    protected void nodeCompleted(Object parentObject node) {
        toState(3, node);
        .flush();
    }
    protected void print(Object node) {
        .print(node == null ? "null" : node.toString());
    }
    protected Object getName(String methodName) {
        return super.getName(methodName);
    }

    
Returns a String with special XML characters escaped as entities so that output XML is valid. Escapes the following characters as corresponding entities:
  • \' as '
  • & as &
  • < as &lt;
  • > as &gt;

Deprecated:
Parameters:
value to be searched and replaced for XML special characters.
Returns:
value with XML characters escaped
See also:
escapeXmlValue(java.lang.String,boolean)
    protected String transformValue(String value) {
        // & has to be checked and replaced before others
        if (value.matches(".*&.*")) {
            value = value.replaceAll("&""&amp;");
        }
        if (value.matches(".*\\'.*")) {
            value = value.replaceAll("\\'""&apos;");
        }
        if (value.matches(".*<.*")) {
            value = value.replaceAll("<""&lt;");
        }
        if (value.matches(".*>.*")) {
            value = value.replaceAll(">""&gt;");
        }
        return value;
    }

    
Escapes a string so that it can be used directly as an XML attribute value.

Parameters:
value The string to escape.
Returns:
A new string in which all characters that require escaping have been replaced with the corresponding XML entities.
See also:
escapeXmlValue(java.lang.String,boolean)
    private String escapeAttributeValue(String value) {
        return escapeXmlValue(valuetrue);
    }

    
Escapes a string so that it can be used directly in XML element content.

Parameters:
value The string to escape.
Returns:
A new string in which all characters that require escaping have been replaced with the corresponding XML entities.
See also:
escapeXmlValue(java.lang.String,boolean)
    private String escapeElementContent(String value) {
        return escapeXmlValue(valuefalse);
    }

    
Escapes a string so that it can be used in XML text successfully. It replaces the following characters with the corresponding XML entities:
  • & as &amp;
  • < as &lt;
  • > as &gt;
If the string is to be added as an attribute value, these characters are also escaped:
  • ' as &apos;

Parameters:
value The string to escape.
isAttrValue true if the string is to be used as an attribute value, otherwise false.
Returns:
A new string in which all characters that require escaping have been replaced with the corresponding XML entities.
    private String escapeXmlValue(String valueboolean isAttrValue) {
        StringBuffer buffer = new StringBuffer(value);
        for (int i = 0, n = buffer.length(); i < ni++) {
            switch (buffer.charAt(i)) {
            case '&':
                buffer.replace(ii + 1, "&amp;");
                // We're replacing a single character by a string of
                // length 5, so we need to update the index variable
                // and the total length.
                i += 4;
                n += 4;
                break;
            case '<':
                buffer.replace(ii + 1, "&lt;");
                // We're replacing a single character by a string of
                // length 4, so we need to update the index variable
                // and the total length.
                i += 3;
                n += 3;
                break;
            case '>':
                buffer.replace(ii + 1, "&gt;");
                // We're replacing a single character by a string of
                // length 4, so we need to update the index variable
                // and the total length.
                i += 3;
                n += 3;
                break;
            case '"':
                // The double quote is only escaped if the value is for
                // an attribute and the builder is configured to output
                // attribute values inside double quotes.
                if (isAttrValue && this.) {
                    buffer.replace(ii + 1, "&quot;");
                    // We're replacing a single character by a string of
                    // length 6, so we need to update the index variable
                    // and the total length.
                    i += 5;
                    n += 5;
                }
                break;
            case '\'':
                // The apostrophe is only escaped if the value is for an
                // attribute, as opposed to element content, and if the
                // builder is configured to surround attribute values with
                // single quotes.
                if (isAttrValue && !this.){
                    buffer.replace(ii + 1, "&apos;");
                    // We're replacing a single character by a string of
                    // length 6, so we need to update the index variable
                    // and the total length.
                    i += 5;
                    n += 5;
                }
                break;
            default:
                break;
            }
        }
        return buffer.toString();
    }
    private void toState(int nextObject name) {
        switch () {
            case 0:
                switch (next) {
                    case 1:
                    case 2:
                        .print("<");
                        print(name);
                        break;
                    case 3:
                        throw new Error();
                }
                break;
            case 1:
                switch (next) {
                    case 1:
                    case 2:
                        .print(">");
                        if () {
                             = false;
                        } else {
                            .println();
                            .incrementIndent();
                            .printIndent();
                        }
                        .print("<");
                        print(name);
                        break;
                    case 3:
                        if () {
                            .print(" />");
                        }
                        break;
                }
                break;
            case 2:
                switch (next) {
                    case 1:
                    case 2:
                        if (!) {
                            .println();
                            .incrementIndent();
                            .printIndent();
                        }
                        .print("<");
                        print(name);
                        break;
                    case 3:
                        .print("</");
                        print(name);
                        .print(">");
                        break;
                }
                break;
            case 3:
                switch (next) {
                    case 1:
                    case 2:
                        if () {
                             = false;
                        } else {
                            .println();
                            .printIndent();
                        }
                        .print("<");
                        print(name);
                        break;
                    case 3:
                        if () {
                             = false;
                        } else {
                            .println();
                            .decrementIndent();
                            .printIndent();
                        }
                        .print("</");
                        print(name);
                        .print(">");
                        break;
                }
                break;
        }
         = next;
    }
    private Object getName(Object name) {
        if (name instanceof QName) {
            return ((QNamename).getQualifiedName();
        }
        return name;
    }
New to GrepCode? Check out our FAQ X