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 - 格式设置工具,用于链接