Skip to content

Commit da36b00

Browse files
committed
Add declaration function to serializers
1 parent dc3a19b commit da36b00

2 files changed

Lines changed: 29 additions & 12 deletions

File tree

‎src/writers/BaseWriter.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ export abstract class BaseWriter<T extends BaseWriterOptions, U extends XMLSeria
3737
*/
3838
abstract serialize(node: Node, writerOptions?: T): U
3939

40+
/**
41+
* Used by derived classes to serialize the XML declaration.
42+
*
43+
* @param version - a version number string
44+
* @param encoding - encoding declaration
45+
* @param standalone - standalone document declaration
46+
*/
47+
declaration(version: "1.0", encoding?: string, standalone?: boolean) { }
48+
4049
/**
4150
* Used by derived classes to serialize a DocType node.
4251
*

‎src/writers/XMLWriter.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,13 @@ export class XMLWriter extends BaseWriter<XMLWriterOptions, string> {
3838

3939
this._refs = { suppressPretty: false, emptyNode: false, markup: "" }
4040

41-
// Serialize XML declaration since base serializer does not serialize it
41+
// Serialize XML declaration
4242
if (node.nodeType === NodeType.Document && !this._options.headless) {
43-
this._beginLine()
44-
this._refs.markup = "<?xml"
45-
this._refs.markup += " version=\"" + this._builderOptions.version + "\""
46-
if (this._builderOptions.encoding !== undefined) {
47-
this._refs.markup += " encoding=\"" + this._builderOptions.encoding + "\""
48-
}
49-
if (this._builderOptions.standalone !== undefined) {
50-
this._refs.markup += " standalone=\"" + (this._builderOptions.standalone ? "yes" : "no") + "\""
51-
}
52-
this._refs.markup += "?>"
53-
this._endLine()
43+
this.declaration(this._builderOptions.version, this._builderOptions.encoding,
44+
this._builderOptions.standalone)
5445
}
5546

47+
// recursively serialize node
5648
this.serializeNode(node, this._options.wellFormed, this._options.noDoubleEncoding)
5749

5850
// remove trailing newline
@@ -64,6 +56,22 @@ export class XMLWriter extends BaseWriter<XMLWriterOptions, string> {
6456
return this._refs.markup
6557
}
6658

59+
/** @inheritdoc */
60+
declaration(version: "1.0", encoding?: string, standalone?: boolean): void {
61+
this._beginLine()
62+
63+
this._refs.markup += "<?xml version=\"" + version + "\""
64+
if (encoding !== undefined) {
65+
this._refs.markup += " encoding=\"" + encoding + "\""
66+
}
67+
if (standalone !== undefined) {
68+
this._refs.markup += " standalone=\"" + (standalone ? "yes" : "no") + "\""
69+
}
70+
this._refs.markup += "?>"
71+
72+
this._endLine()
73+
}
74+
6775
/** @inheritdoc */
6876
docType(name: string, publicId: string, systemId: string): void {
6977
this._beginLine()

0 commit comments

Comments
 (0)