001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.xml;
016
017import com.google.common.annotations.Beta;
018import com.google.common.annotations.GwtCompatible;
019import com.google.common.escape.Escaper;
020import com.google.common.escape.Escapers;
021
022/**
023 * {@code Escaper} instances suitable for strings to be included in XML attribute values and
024 * elements' text contents. When possible, avoid manual escaping by using templating systems and
025 * high-level APIs that provide autoescaping. For example, consider <a
026 * href="http://www.xom.nu/">XOM</a> or <a href="http://www.jdom.org/">JDOM</a>.
027 *
028 * <p><b>Note:</b> Currently the escapers provided by this class do not escape any characters
029 * outside the ASCII character range. Unlike HTML escaping the XML escapers will not escape
030 * non-ASCII characters to their numeric entity replacements. These XML escapers provide the minimal
031 * level of escaping to ensure that the output can be safely included in a Unicode XML document.
032 *
033 * <p>For details on the behavior of the escapers in this class, see sections <a
034 * href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">2.2</a> and <a
035 * href="http://www.w3.org/TR/2008/REC-xml-20081126/#syntax">2.4</a> of the XML specification.
036 *
037 * @author Alex Matevossian
038 * @author David Beaumont
039 * @since 15.0
040 */
041@Beta
042@GwtCompatible
043public class XmlEscapers {
044  private XmlEscapers() {}
045
046  private static final char MIN_ASCII_CONTROL_CHAR = 0x00;
047  private static final char MAX_ASCII_CONTROL_CHAR = 0x1F;
048
049  // For each xxxEscaper() method, please add links to external reference pages
050  // that are considered authoritative for the behavior of that escaper.
051
052  /**
053   * Returns an {@link Escaper} instance that escapes special characters in a string so it can
054   * safely be included in an XML document as element content. See section <a
055   * href="http://www.w3.org/TR/2008/REC-xml-20081126/#syntax">2.4</a> of the XML specification.
056   *
057   * <p><b>Note:</b> Double and single quotes are not escaped, so it is <b>not safe</b> to use this
058   * escaper to escape attribute values. Use {@link #xmlContentEscaper} if the output can appear in
059   * element content or {@link #xmlAttributeEscaper} in attribute values.
060   *
061   * <p>This escaper substitutes {@code 0xFFFD} for non-whitespace control characters and the
062   * character values {@code 0xFFFE} and {@code 0xFFFF} which are not permitted in XML. For more
063   * detail see section <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">2.2</a> of
064   * the XML specification.
065   *
066   * <p>This escaper does not escape non-ASCII characters to their numeric character references
067   * (NCR). Any non-ASCII characters appearing in the input will be preserved in the output.
068   * Specifically "\r" (carriage return) is preserved in the output, which may result in it being
069   * silently converted to "\n" when the XML is parsed.
070   *
071   * <p>This escaper does not treat surrogate pairs specially and does not perform Unicode
072   * validation on its input.
073   */
074  public static Escaper xmlContentEscaper() {
075    return XML_CONTENT_ESCAPER;
076  }
077
078  /**
079   * Returns an {@link Escaper} instance that escapes special characters in a string so it can
080   * safely be included in XML document as an attribute value. See section <a
081   * href="http://www.w3.org/TR/2008/REC-xml-20081126/#AVNormalize">3.3.3</a> of the XML
082   * specification.
083   *
084   * <p>This escaper substitutes {@code 0xFFFD} for non-whitespace control characters and the
085   * character values {@code 0xFFFE} and {@code 0xFFFF} which are not permitted in XML. For more
086   * detail see section <a href="http://www.w3.org/TR/2008/REC-xml-20081126/#charsets">2.2</a> of
087   * the XML specification.
088   *
089   * <p>This escaper does not escape non-ASCII characters to their numeric character references
090   * (NCR). However, horizontal tab {@code '\t'}, line feed {@code '\n'} and carriage return {@code
091   * '\r'} are escaped to a corresponding NCR {@code "&#x9;"}, {@code "&#xA;"}, and {@code "&#xD;"}
092   * respectively. Any other non-ASCII characters appearing in the input will be preserved in the
093   * output.
094   *
095   * <p>This escaper does not treat surrogate pairs specially and does not perform Unicode
096   * validation on its input.
097   */
098  public static Escaper xmlAttributeEscaper() {
099    return XML_ATTRIBUTE_ESCAPER;
100  }
101
102  private static final Escaper XML_ESCAPER;
103  private static final Escaper XML_CONTENT_ESCAPER;
104  private static final Escaper XML_ATTRIBUTE_ESCAPER;
105
106  static {
107    Escapers.Builder builder = Escapers.builder();
108    // The char values \uFFFE and \uFFFF are explicitly not allowed in XML
109    // (Unicode code points above \uFFFF are represented via surrogate pairs
110    // which means they are treated as pairs of safe characters).
111    builder.setSafeRange(Character.MIN_VALUE, '\uFFFD');
112    // Unsafe characters are replaced with the Unicode replacement character.
113    builder.setUnsafeReplacement("\uFFFD");
114
115    /*
116     * Except for \n, \t, and \r, all ASCII control characters are replaced with the Unicode
117     * replacement character.
118     *
119     * Implementation note: An alternative to the following would be to make a map that simply
120     * replaces the allowed ASCII whitespace characters with themselves and to set the minimum safe
121     * character to 0x20. However this would slow down the escaping of simple strings that contain
122     * \t, \n, or \r.
123     */
124    for (char c = MIN_ASCII_CONTROL_CHAR; c <= MAX_ASCII_CONTROL_CHAR; c++) {
125      if (c != '\t' && c != '\n' && c != '\r') {
126        builder.addEscape(c, "\uFFFD");
127      }
128    }
129
130    // Build the content escaper first and then add quote escaping for the
131    // general escaper.
132    builder.addEscape('&', "&amp;");
133    builder.addEscape('<', "&lt;");
134    builder.addEscape('>', "&gt;");
135    XML_CONTENT_ESCAPER = builder.build();
136    builder.addEscape('\'', "&apos;");
137    builder.addEscape('"', "&quot;");
138    XML_ESCAPER = builder.build();
139    builder.addEscape('\t', "&#x9;");
140    builder.addEscape('\n', "&#xA;");
141    builder.addEscape('\r', "&#xD;");
142    XML_ATTRIBUTE_ESCAPER = builder.build();
143  }
144}