Class Format

格式

用于输出 XML 文档的格式设置工具,具有三种可进一步自定义的预定义格式。

// Log an XML document with specified formatting options.
var xml = '<root><a><b>Text!</b><b>More text!</b></a></root>';
var document = XmlService.parse(xml);
var output = XmlService.getCompactFormat()
    .setLineSeparator('\n')
    .setEncoding('UTF-8')
    .setIndent('   ')
    .format(document);
Logger.log(output);

方法

方法返回类型简介
format(document)String以格式化字符串的形式输出给定的 Document
format(element)String以格式化字符串输出指定的 Element 节点。
setEncoding(encoding)Format设置格式设置工具应使用的字符编码。
setIndent(indent)Format设置用于缩进其子节点相对于其父节点的字符串。
setLineSeparator(separator)Format设置在格式化程序通常要插入换行符时要插入的字符串。
setOmitDeclaration(omitDeclaration)Format设置格式设置工具是否应省略 XML 声明,例如 <?xml version="1.0" encoding="UTF-8"?>
setOmitEncoding(omitEncoding)Format设置格式化程序是否应忽略 XML 声明中的编码,例如 <?xml version="1.0" encoding="UTF-8"?> 中的编码字段。

详细文档

format(document)

以格式化字符串的形式输出给定的 Document

参数

名称类型说明
documentDocument要设置格式的文档

返回

String - 格式化的文档


format(element)

以格式化字符串输出指定的 Element 节点。

参数

名称类型说明
elementElement要设置格式的元素

返回

String - 格式化元素


setEncoding(encoding)

设置格式设置工具应使用的字符编码。encoding 参数必须是可接受的 XML 编码,例如 ISO-8859-1US-ASCIIUTF-8UTF-16

// Log an XML document with encoding that does not support certain special characters.
var xml = '<root><a><b>ಠ‿ಠ</b><b>ಠ‿ಠ</b></a></root>';
var document = XmlService.parse(xml);
var output = XmlService.getRawFormat()
    .setEncoding('ISO-8859-1')
    .format(document);
Logger.log(output);

参数

名称类型说明
encodingString要使用的编码

返回

Format - 用于链接的格式化程序


setIndent(indent)

设置用于缩进其子节点相对于其父节点的字符串。设置 null 以外的缩进会导致格式设置工具在每个节点后插入换行符。

// Log an XML document with each child node indented four spaces.
var xml = '<root><a><b>Text!</b><b>More text!</b></a></root>';
var document = XmlService.parse(xml);
var output = XmlService.getCompactFormat()
    .setIndent('    ')
    .format(document);
Logger.log(output);

参数

名称类型说明
indentString要使用的缩进

返回

Format - 用于链接的格式化程序


setLineSeparator(separator)

设置在格式化程序通常要插入换行符时要插入的字符串。三种预定义的格式化程序会在不同的条件下插入换行符。默认行分隔符是 \r\n

// Log an XML document with several spaces and a pipe character in place of line breaks.
var xml = '<root><a><b>Text!</b><b>More text!</b></a></root>';
var document = XmlService.parse(xml);
var output = XmlService.getRawFormat()
    .setLineSeparator(' | ')
    .format(document);
Logger.log(output);

参数

名称类型说明
separatorString要使用的分隔符

返回

Format - 用于链接的格式化程序


setOmitDeclaration(omitDeclaration)

设置格式设置工具是否应省略 XML 声明,例如 <?xml version="1.0" encoding="UTF-8"?>

参数

名称类型说明
omitDeclarationBooleantrue(用于省略 XML 声明);使用 false(用于包含)

返回

Format - 用于链接的格式化程序


setOmitEncoding(omitEncoding)

设置格式化程序是否应忽略 XML 声明中的编码,例如 <?xml version="1.0" encoding="UTF-8"?> 中的编码字段。

参数

名称类型说明
omitEncodingBooleantrue,用于在 XML 声明中省略编码;使用 false 以包含该声明

返回

Format - 用于链接的格式化程序