RFC 7303 and character encoding precedence in XML transfers
Trace how the July 2014 standard reconciles XML bytes, MIME character encoding and XML declarations in three local Node.js fixtures.
Archive retrospective · Topic year 2014
In this article
Start with the bytes that carry the name
Imagine a city publishing its daily transit schedule in XML to two partners. Both expect to see İzmir in the same stop record. One hands the response bytes to an XML library, while the other gets a JavaScript string from its transport utility. If the utility chose the wrong encoding, the tree can parse successfully with the wrong text in the stop name. An index or an identifier derived from that name can turn the difference into a second record. RFC 7303, published in July 2014, revisited the XML media types and specified how to resolve conflicting encoding information. To investigate a discrepancy, record the response media type and inspect the original bytes before text conversion. The media type identifies the content as XML. A charset parameter, when supplied, identifies its expected character encoding. Copying the metadata from a different object or rebuilding a response header can change what a consumer selects even when the payload bytes stay identical.
Use the order specified for XML MIME entities
A byte order mark takes precedence when present at the beginning of an XML MIME entity. For example, the prefix FF FE in the fixture signals UTF-16 little-endian. A receiver can identify it even if the Content-Type header incorrectly names UTF-8. Without a BOM, a supplied MIME charset is authoritative. If neither source is available, the receiver falls back to XML processing rules, which include the encoding declaration and XML’s defaults. Keeping that decision in one layer avoids independent guesses by consumers of the same message. A conforming producer keeps its declarations and actual encoding consistent. UTF-8 input may carry the signature EF BB BF. XML explicitly labeled utf-16le or utf-16be has a separate rule and must start without a BOM. The first fixture is ordinary UTF-16 XML with a mark and an intentionally conflicting header value. Changing a label alone never converts the original bytes.
Run three fixtures with the same city name
The local example reads a fixed field from three inputs without installing an XML library. The first combines a UTF-16LE byte order mark and a conflicting UTF-8 header. The second has a UTF-8 header and no mark. The third has no charset and carries a UTF-8 mark. The decoder receives the bytes after the signature, so the mark stays outside markup and character data. All three return İzmir. Running the example on Node.js 24.19.0 reported utf-16le for the first input and utf-8 for the other two. A fourth assertion checks that a malformed UTF-8 byte sequence raises an error. The regular expression only extracts a value from a fixed fixture. The sample supports just two encodings and leaves the XML declaration detection path to an actual parser. In production, preserve the original input and the MIME metadata until that component can make its encoding decision.
import assert from 'node:assert/strict';
const label = '<city>İzmir</city>';
const declaration = encoding => `<?xml version="1.0" encoding="${encoding}"?>${label}`;
const utf8 = Buffer.from(declaration('UTF-8'));
const utf16 = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(declaration('UTF-16'), 'utf16le')]);
// Only the two encodings and byte-order marks used in these fixtures.
function readFixture(bytes, charset) {
const prefix = bytes.subarray(0, 3).toString('hex');
const bom = prefix.startsWith('fffe') ? {encoding:'utf-16le', size:2}
: prefix === 'efbbbf' ? {encoding:'utf-8', size:3}
: undefined;
const encoding = bom?.encoding ?? charset;
assert(['utf-8', 'utf-16le'].includes(encoding));
const decoded = new TextDecoder(encoding, {fatal:true}).decode(bytes.subarray(bom?.size ?? 0));
return {encoding, city:decoded.match(/<city>([^<]*)<\/city>/u)?.[1]};
}
const cases = [
{case:'UTF-16LE BOM, conflicting UTF-8 header', ...readFixture(utf16, 'utf-8')},
{case:'UTF-8 header, no BOM', ...readFixture(utf8, 'utf-8')},
{case:'no charset, UTF-8 BOM', ...readFixture(Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), utf8]))}
];
assert.deepEqual(cases.map(row => [row.encoding, row.city]), [['utf-16le','İzmir'],['utf-8','İzmir'],['utf-8','İzmir']]);
assert.throws(() => readFixture(Buffer.from([0x3c, 0xc3, 0x28, 0x3e]), 'utf-8'), TypeError);
console.log(JSON.stringify({node:process.version, cases, invalidUtf8:'rejected'}, null, 2));
Keep transport decoding and text decoding separate
A gateway receiving a compressed HTTP body removes transport content coding before it reasons about the XML entity. Decompression leaves the character encoding intact. An object store republishing a file can preserve its media type and charset. If the service re-encodes the text, it also needs to revisit the media parameters and the XML declaration. A mismatch can show up in one client and remain hidden in another. XML encoding rules still matter outside an HTTP transaction. A local file, for example, has no response header at all. If it has no mark, the document declaration or the XML default becomes relevant. Once a gateway discards the original bytes, looking at the first characters of a repaired string cannot establish whether the incoming object carried a mark. Use synthetic fixtures for byte dumps and use metadata or test identifiers in ordinary operational logs.
Assert the value as well as the parse result
Successful tree construction is only the first assertion in a transport test. Compare a field containing distinctive characters with its expected value. ASCII-only fixtures frequently pass even when a header and a byte sequence disagree. Include matching UTF-8 cases both with and without a mark, plus a general UTF-16 case if the integration supports it. Use matching fixtures to check producers. Keep a conflict case to check what the consumer does when those producers make a mistake. A receiver might log the mismatch and continue according to the specification. An integration with a stricter contract could quarantine the message and ask for a replacement. That decision sits above the encoding precedence rule. Run the same fixture set through both receiving and forwarding paths so that a component that reads correctly but emits an incorrect label is caught before deployment.
Connect the 2014 specification to a current test
RFC 7303 superseded RFC 3023. Its date describes when the standard changed, while the recorded Node version identifies the environment that ran this particular demonstration. A small repeatable test can survive a change of HTTP client or storage adapter because it compares observable output. Review where the new client reads headers, where bytes become text, and what error comes back when the encoding is invalid. The test receipt therefore records the selected encoding, the expected field value and the result for malformed bytes. Those checks make it possible to compare both ends of an integration before damaged characters reach downstream indexes or exported files.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment