コード例 #1
0
 /**
  * Pretty prints the given node
  *
  * @param node the node, usually a document, to be printed
  * @param prefs the formatting preferences
  * @param style the formatting style to use
  * @param lineSeparator the line separator to use, or null to use the default
  * @param endWithNewline if true, ensure that the printed output ends with a newline
  * @return a formatted string
  */
 @NonNull
 public static String prettyPrint(
     @NonNull Node node,
     @NonNull XmlFormatPreferences prefs,
     @NonNull XmlFormatStyle style,
     @Nullable String lineSeparator,
     boolean endWithNewline) {
   XmlPrettyPrinter printer = new XmlPrettyPrinter(prefs, style, lineSeparator);
   printer.setEndWithNewline(endWithNewline);
   StringBuilder sb = new StringBuilder(1000);
   printer.prettyPrint(-1, node, null, null, sb, false /*openTagOnly*/);
   String xml = sb.toString();
   if (node.getNodeType() == Node.DOCUMENT_NODE && !xml.startsWith("<?")) { // $NON-NLS-1$
     xml = XML_PROLOG + xml;
   }
   return xml;
 }
コード例 #2
0
 /**
  * Pretty-prints the given XML document, which must be well-formed. If it is not, the original
  * unformatted XML document is returned
  *
  * @param xml the XML content to format
  * @param prefs the preferences to format with
  * @param style the style to format with
  * @param lineSeparator the line separator to use, such as "\n" (can be null, in which case the
  *     system default is looked up via the line.separator property)
  * @return the formatted document (or if a parsing error occurred, returns the unformatted
  *     document)
  */
 @NonNull
 public static String prettyPrint(
     @NonNull String xml,
     @NonNull XmlFormatPreferences prefs,
     @NonNull XmlFormatStyle style,
     @Nullable String lineSeparator) {
   Document document = XmlUtils.parseDocumentSilently(xml, true);
   if (document != null) {
     XmlPrettyPrinter printer = new XmlPrettyPrinter(prefs, style, lineSeparator);
     printer.setEndWithNewline(xml.endsWith(printer.getLineSeparator()));
     StringBuilder sb = new StringBuilder(3 * xml.length() / 2);
     printer.prettyPrint(-1, document, null, null, sb, false /*openTagOnly*/);
     return sb.toString();
   } else {
     // Parser error: just return the unformatted content
     return xml;
   }
 }