用于输出 XML 文档的格式设置程序,其中包含三种可进一步自定义的预定义格式。
// Log an XML document with specified formatting options. const xml = '<root><a><b>Text!</b><b>More text!</b></a></root>'; const document = XmlService.parse(xml); const output = XmlService.getCompactFormat() .setLineSeparator('\n') .setEncoding('UTF-8') .setIndent(' ') .format(document); Logger.log(output);
方法
| 方法 | 返回类型 | 简介 |
|---|---|---|
format(document) | String | 以格式化字符串的形式输出给定的 Document。 |
format(element) | String | 将指定的 Element 节点输出为格式化字符串。 |
set | Format | 设置格式化程序应使用的字符编码。 |
set | Format | 设置用于相对于父节点缩进子节点的字符串。 |
set | Format | 设置在格式化程序通常会插入换行符时要插入的字符串。 |
set | Format | 设置格式化程序是否应省略 XML 声明,例如 <?xml version="1.0"
encoding="UTF-8"?>。 |
set | Format | 设置格式化程序是否应忽略 XML 声明中的编码,例如 <?xml version="1.0" encoding="UTF-8"?> 中的编码字段。 |
详细文档
set Encoding(encoding)
设置格式化程序应使用的字符编码。encoding 参数必须是接受的 XML 编码,例如 ISO-8859-1、US-ASCII、UTF-8 或 UTF-16。
// Log an XML document with encoding that does not support certain special // characters. const xml = '<root><a><b>ಠ‿ಠ</b><b>ಠ‿ಠ</b></a></root>'; const document = XmlService.parse(xml); const output = XmlService.getRawFormat().setEncoding('ISO-8859-1').format(document); Logger.log(output);
参数
| 名称 | 类型 | 说明 |
|---|---|---|
encoding | String | 要使用的编码 |
返回
Format - 用于链式调用的格式设置工具
set Indent(indent)
设置用于相对于父节点缩进子节点的字符串。设置 null 以外的缩进会导致格式设置程序在每个节点后插入换行符。
// Log an XML document with each child node indented four spaces. const xml = '<root><a><b>Text!</b><b>More text!</b></a></root>'; const document = XmlService.parse(xml); const output = XmlService.getCompactFormat().setIndent(' ').format(document); Logger.log(output);
参数
| 名称 | 类型 | 说明 |
|---|---|---|
indent | String | 要使用的缩进 |
返回
Format - 用于链式调用的格式设置工具
set Line Separator(separator)
设置在格式化程序通常会插入换行符时要插入的字符串。这三种预定义的格式化程序在插入换行符时具有不同的条件。默认行分隔符为 \r\n。
// Log an XML document with several spaces and a pipe character in place of line // breaks. const xml = '<root><a><b>Text!</b><b>More text!</b></a></root>'; const document = XmlService.parse(xml); const output = XmlService.getRawFormat().setLineSeparator(' | ').format(document); Logger.log(output);
参数
| 名称 | 类型 | 说明 |
|---|---|---|
separator | String | 要使用的分隔符 |
返回
Format - 用于链式调用的格式设置工具
set Omit Declaration(omitDeclaration)
设置格式化程序是否应省略 XML 声明,例如 <?xml version="1.0"
encoding="UTF-8"?>。
参数
| 名称 | 类型 | 说明 |
|---|---|---|
omit | Boolean | true 表示省略 XML 声明;false 表示包含该声明 |
返回
Format - 用于链式调用的格式设置工具
set Omit Encoding(omitEncoding)
设置格式化程序是否应忽略 XML 声明中的编码,例如 <?xml version="1.0" encoding="UTF-8"?> 中的编码字段。
参数
| 名称 | 类型 | 说明 |
|---|---|---|
omit | Boolean | true 表示在 XML 声明中省略编码;false 表示包含编码 |
返回
Format - 用于链式调用的格式设置工具