0
# XML Serialization
1
2
Convert DOM nodes back into XML strings with optional filtering and formatting control. Provides standards-compliant XML output generation.
3
4
## Capabilities
5
6
### XMLSerializer Class
7
8
The main serialization class that converts DOM nodes into XML string representations.
9
10
```javascript { .api }
11
/**
12
* Serializes DOM nodes to XML strings
13
* Provides control over output formatting and node filtering
14
*/
15
class XMLSerializer {
16
constructor();
17
18
/**
19
* Serializes a DOM node and its descendants to an XML string
20
* @param node - The root node to serialize
21
* @param nodeFilter - Optional function to filter which nodes to include
22
* @returns XML string representation of the node tree
23
*/
24
serializeToString(node: Node, nodeFilter?: (node: Node) => boolean): string;
25
}
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
const { DOMParser, XMLSerializer } = require('@xmldom/xmldom');
32
33
// Parse and serialize basic document
34
const parser = new DOMParser();
35
const doc = parser.parseFromString('<root><child>content</child></root>', 'text/xml');
36
37
const serializer = new XMLSerializer();
38
const xmlString = serializer.serializeToString(doc);
39
console.log(xmlString); // <?xml version="1.0"?><root><child>content</child></root>
40
41
// Serialize specific elements
42
const root = doc.documentElement;
43
const rootXml = serializer.serializeToString(root);
44
console.log(rootXml); // <root><child>content</child></root>
45
46
// Serialize with node filtering
47
const filteredXml = serializer.serializeToString(doc, (node) => {
48
// Only include element nodes and text nodes
49
return node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE;
50
});
51
```
52
53
### Serialization Behavior
54
55
The serializer handles different node types according to XML standards:
56
57
**Document Nodes:**
58
- Includes XML declaration if present
59
- Serializes document element and any processing instructions or comments at document level
60
61
**Element Nodes:**
62
- Outputs start and end tags with proper namespace declarations
63
- Includes all attributes in the output
64
- Handles void elements and empty elements appropriately
65
66
**Text Nodes:**
67
- Escapes special XML characters (`<`, `>`, `&`)
68
- Preserves whitespace as specified in the DOM
69
70
**CDATA Sections:**
71
- Outputs content within `<![CDATA[...]]>` markers
72
- Content is not escaped within CDATA sections
73
74
**Comments:**
75
- Outputs as `<!-- ... -->` format
76
- Ensures comment content doesn't contain invalid sequences
77
78
**Processing Instructions:**
79
- Outputs as `<?target data?>` format
80
- Handles XML declaration processing instructions specially
81
82
### Advanced Usage
83
84
**Filtering Nodes:**
85
86
```javascript
87
const { DOMParser, XMLSerializer, Node } = require('@xmldom/xmldom');
88
89
const parser = new DOMParser();
90
const doc = parser.parseFromString(`
91
<root>
92
<!-- This is a comment -->
93
<data>Important content</data>
94
<metadata>Skip this</metadata>
95
<?instruction data?>
96
</root>
97
`, 'text/xml');
98
99
const serializer = new XMLSerializer();
100
101
// Only serialize elements and text, skip comments and PIs
102
const elementsOnly = serializer.serializeToString(doc, (node) => {
103
return node.nodeType === Node.ELEMENT_NODE ||
104
node.nodeType === Node.TEXT_NODE ||
105
node.nodeType === Node.DOCUMENT_NODE;
106
});
107
108
// Skip specific elements by tag name
109
const skipMetadata = serializer.serializeToString(doc, (node) => {
110
if (node.nodeType === Node.ELEMENT_NODE) {
111
return node.nodeName !== 'metadata';
112
}
113
return true;
114
});
115
```
116
117
**Handling Different Document Types:**
118
119
```javascript
120
// Serialize HTML document
121
const htmlDoc = parser.parseFromString('<html><body><p>Hello</p></body></html>', 'text/html');
122
const htmlString = serializer.serializeToString(htmlDoc);
123
124
// Serialize with namespaces
125
const nsDoc = parser.parseFromString(`
126
<root xmlns="http://example.com" xmlns:ns="http://other.com">
127
<child>Default namespace</child>
128
<ns:child>Other namespace</ns:child>
129
</root>
130
`, 'text/xml');
131
const nsString = serializer.serializeToString(nsDoc);
132
// Preserves namespace declarations and prefixes
133
```
134
135
**Working with Document Fragments:**
136
137
```javascript
138
const fragment = doc.createDocumentFragment();
139
const elem1 = doc.createElement('item');
140
elem1.textContent = 'First item';
141
const elem2 = doc.createElement('item');
142
elem2.textContent = 'Second item';
143
144
fragment.appendChild(elem1);
145
fragment.appendChild(elem2);
146
147
// Serialize fragment (outputs child nodes without wrapper)
148
const fragmentXml = serializer.serializeToString(fragment);
149
console.log(fragmentXml); // <item>First item</item><item>Second item</item>
150
```
151
152
**Character Encoding and Escaping:**
153
154
The serializer automatically handles XML character escaping:
155
156
```javascript
157
const doc = parser.parseFromString('<root></root>', 'text/xml');
158
const element = doc.createElement('test');
159
160
// Special characters are automatically escaped
161
element.setAttribute('data', 'value with & < > " characters');
162
element.textContent = 'Text with <script> & "quotes"';
163
164
const escaped = serializer.serializeToString(element);
165
// Output: <test data="value with & < > " characters">Text with <script> & "quotes"</test>
166
```
167
168
**Error Handling:**
169
170
```javascript
171
try {
172
const result = serializer.serializeToString(someNode);
173
} catch (error) {
174
console.error('Serialization failed:', error.message);
175
// Handle cases like invalid node structures or circular references
176
}
177
```
178
179
### Integration with DOM Manipulation
180
181
Serialization works seamlessly with all DOM manipulation operations:
182
183
```javascript
184
const { DOMParser, XMLSerializer } = require('@xmldom/xmldom');
185
186
// Create and modify document
187
const parser = new DOMParser();
188
const doc = parser.parseFromString('<catalog></catalog>', 'text/xml');
189
190
// Add items dynamically
191
const catalog = doc.documentElement;
192
for (let i = 1; i <= 3; i++) {
193
const item = doc.createElement('item');
194
item.setAttribute('id', i.toString());
195
item.textContent = `Item ${i}`;
196
catalog.appendChild(item);
197
}
198
199
// Serialize the modified document
200
const serializer = new XMLSerializer();
201
const result = serializer.serializeToString(doc);
202
console.log(result);
203
// Output: <?xml version="1.0"?><catalog><item id="1">Item 1</item><item id="2">Item 2</item><item id="3">Item 3</item></catalog>
204
```
205
206
### Output Formatting
207
208
The serializer produces compact XML output without additional formatting. For pretty-printed output, you would need to implement custom formatting or use external tools:
209
210
```javascript
211
// The serializer produces compact output
212
const compactXml = serializer.serializeToString(doc);
213
// <root><child><grandchild>content</grandchild></child></root>
214
215
// For formatted output, you'd need to implement custom logic
216
function formatXml(xmlString) {
217
// Custom formatting implementation
218
// This is not provided by @xmldom/xmldom
219
}
220
```