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 — 用於鏈結的格式設定工具