/**
  * Pretty prints the given node using default styles
  *
  * @param node the node, usually a document, to be printed
  * @param endWithNewline if true, ensure that the printed output ends with a newline
  * @return the resulting formatted string
  */
 @NonNull
 public static String prettyPrint(@NonNull Node node, boolean endWithNewline) {
   return prettyPrint(
       node,
       XmlFormatPreferences.defaults(),
       XmlFormatStyle.get(node),
       SdkUtils.getLineSeparator(),
       endWithNewline);
 }
  private static void formatFile(@NonNull XmlFormatPreferences prefs, File file, boolean stdout) {
    if (file.isDirectory()) {
      File[] files = file.listFiles();
      if (files != null) {
        for (File child : files) {
          formatFile(prefs, child, stdout);
        }
      }
    } else if (file.isFile() && SdkUtils.endsWithIgnoreCase(file.getName(), DOT_XML)) {
      XmlFormatStyle style = null;
      if (file.getName().equals(SdkConstants.ANDROID_MANIFEST_XML)) {
        style = XmlFormatStyle.MANIFEST;
      } else {
        File parent = file.getParentFile();
        if (parent != null) {
          String parentName = parent.getName();
          ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
          if (folderType == ResourceFolderType.LAYOUT) {
            style = XmlFormatStyle.LAYOUT;
          } else if (folderType == ResourceFolderType.VALUES) {
            style = XmlFormatStyle.RESOURCE;
          }
        }
      }

      try {
        String xml = Files.toString(file, Charsets.UTF_8);
        Document document = XmlUtils.parseDocumentSilently(xml, true);
        if (document == null) {
          System.err.println("Could not parse " + file);
          System.exit(1);
          return;
        }

        if (style == null) {
          style = XmlFormatStyle.get(document);
        }
        boolean endWithNewline = xml.endsWith("\n");
        int firstNewLine = xml.indexOf('\n');
        String lineSeparator =
            firstNewLine > 0 && xml.charAt(firstNewLine - 1) == '\r' ? "\r\n" : "\n";
        String formatted =
            XmlPrettyPrinter.prettyPrint(document, prefs, style, lineSeparator, endWithNewline);
        if (stdout) {
          System.out.println(formatted);
        } else {
          Files.write(formatted, file, Charsets.UTF_8);
        }
      } catch (IOException e) {
        System.err.println("Could not read " + file);
        System.exit(1);
      }
    }
  }