PureXML/Sources/Emitting/Escaping.swift
Mihaela Mihaljevic cd2f30a262 feat(emitting): attribute quote style, line endings, xml:space, writer namespaces
Broaden the serializer and writer options from the audit:

- attributeQuote selects single or double quotes; the active quote is
  escaped in values (apostrophe as ' in single-quote mode).
- lineEnding controls the inserted newline (set to CRLF for \r\n output).
- xml:space=preserve suppresses pretty-print indentation for an element
  and its subtree; xml:space=default re-enables it.
- Writer gains writeStartElementNS(prefix:localName:namespaceURI:) and
  writeNamespace(prefix:uri:), so callers no longer hand-format prefixes
  and xmlns attributes.

CDATA-vs-escape and entity re-escaping strategies are left as a
follow-up; the current escaping is the safe default.

Closes #91
2026-06-08 15:24:49 +02:00

42 lines
1.5 KiB
Swift

extension PureXML.Emitting {
/// The shared XML output escaping rules, used by both the tree serializer and
/// the incremental writer so their output is identical. Element content
/// escapes the markup characters; attribute values additionally escape the
/// quote and the whitespace characters as numeric references (matching
/// libxml2), so attributes survive attribute-value normalization.
enum Escaping {
static func text(_ value: String) -> String {
var result = ""
for character in value {
switch character {
case "&": result += "&"
case "<": result += "&lt;"
case ">": result += "&gt;"
default: result.append(character)
}
}
return result
}
static func attribute(_ value: String, quote: Character = "\"") -> String {
var result = ""
for character in value {
if character == quote {
result += quote == "'" ? "&apos;" : "&quot;"
continue
}
switch character {
case "&": result += "&amp;"
case "<": result += "&lt;"
case ">": result += "&gt;"
case "\t": result += "&#9;"
case "\n": result += "&#10;"
case "\r": result += "&#13;"
default: result.append(character)
}
}
return result
}
}
}