An object containing attribute names as keys and their values as strings
A formatted string of XML attributes ready to be inserted into an XML tag
// Basic attribute formatting
formatAttributes({ version: '1.0', lang: 'en-US' });
// Returns: 'version="1.0" lang="en-US"'
// Filtering undefined values
formatAttributes({
name: 'en-US-AvaNeural',
effect: undefined,
pitch: 'high'
});
// Returns: 'name="en-US-AvaNeural" pitch="high"'
// Empty object returns empty string
formatAttributes({});
// Returns: ''
// All undefined values
formatAttributes({ a: undefined, b: undefined });
// Returns: ''
// Use in XML element construction
const attrs = formatAttributes({
version: '1.0',
xmlns: 'http://www.w3.org/2001/10/synthesis',
'xml:lang': 'en-US'
});
const xml = `<speak ${attrs}>content</speak>`;
// Result: '<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">content</speak>'
// With SSML voice attributes
const voiceAttrs = formatAttributes({
name: 'en-US-AvaNeural',
effect: 'eq_telecomhp8k'
});
const voiceElement = `<voice ${voiceAttrs}>Hello</voice>`;
// Result: '<voice name="en-US-AvaNeural" effect="eq_telecomhp8k">Hello</voice>'
// Security consideration - escape values first if needed
const userProvidedName = escapeXml(getUserInput());
const safeAttrs = formatAttributes({
name: userProvidedName // Already escaped
});
For security reasons, always validate and escape attribute values before using this function, especially when dealing with user-provided input.
Formats a record of attributes into a valid XML attribute string.
This function takes an object containing attribute key-value pairs and converts it into a properly formatted XML attribute string. It automatically:
⚠️ Important Security Note: This function does NOT escape the attribute values. If attribute values contain special characters, they should be escaped before being passed to this function or the escaping should be handled at the element level. Using unescaped user input as attribute values can lead to XML injection vulnerabilities.