Class Format

格式

用於輸出 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 節點。
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.
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);

參數

名稱類型說明
encodingString要使用的編碼。

回攻員

Format:用於串連的格式轉換程式。


setIndent(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);

參數

名稱類型說明
indentString要使用的縮排。

回攻員

Format:用於串連的格式轉換程式。


setLineSeparator(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);

參數

名稱類型說明
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:用於串連的格式轉換程式。