An ampersand in an article title or a query-bearing link can break a hand-built XML feed. A hurried escape fix can create a second problem: the XML parses, but subscribers receive literal entity text or the sitemap points to a changed URL. Test both syntax and preservation of the original values.
Keep one approved input record outside the serializer. Generate XML, parse the actual bytes and compare the decoded fields with that record. A successful parse is necessary for this fixture, but it does not prove the publisher preserved the article’s title, explanation or destination.
The feed identity guide governs GUIDs and real publication history across revisions. This check leaves those identities and dates alone. It tests the separate boundary where ordinary editorial text becomes XML.
Use XML rules rather than HTML or JSON assumptions
The XML 1.0 specification defines character data, entity references, CDATA sections and permitted characters. A literal ampersand or less-than sign in ordinary character data needs the correct serialized treatment. Some Unicode controls are not legal XML 1.0 characters at all.
Wrapping arbitrary editorial text in CDATA is not a universal escape strategy. The sequence that closes a CDATA section can appear in legitimate technical prose. A serializer that writes ordinary text nodes can escape markup-sensitive characters without asking editors to delete accurate examples.
Do not reuse the JSON-LD embedding recipe mechanically. XML, JSON strings and HTML script content have different grammars. The right test decodes the actual publication format instead of treating all angle-bracket problems as the same encoding issue.
Write the expected field values first
The fictional record below includes an accented title, markup-like text and a URL containing both a percent-encoded slash value and a query separator. Those inputs test different preservation boundaries. They do not describe a production article or a real release.
| Input field | Approved decoded value | Boundary tested |
|---|---|---|
| Title | Café & cost <examples> | Non-ASCII and markup-sensitive text |
| Text | Literal ]]> and A stay text. | CDATA terminator and literal entity-looking prose |
| URL | https://docs.example/guides?q=a%2Fb&lang=fr | Percent escapes retained; query separator restored after XML parsing |
The parsed URL should contain its ordinary ampersand separator. The serialized XML should encode that separator appropriately for XML. Do not apply URL percent encoding to the entire URL merely because it will appear inside a loc or link text node; doing so can change its meaning.
For this teaching record the text contains no carriage returns. XML has line-ending normalization rules, so an arbitrary byte-for-byte text promise would be too broad. If imported content relies on carriage returns or other normalization-sensitive characters, define and test that field policy separately.
Run a bounded standard-library fixture
This complete Python example creates an intentionally small XML document, not a full RSS or sitemap schema. It uses only the standard library, performs no network requests and checks the actual generated bytes with an XML parser.
import html
import xml.etree.ElementTree as ET
approved = {
'title': 'Café & cost <examples>',
'text': 'Literal ]]> and A stay text.',
'url': 'https://docs.example/guides?q=a%2Fb&lang=fr',
}
def xml10_char(c):
n = ord(c)
return (n in (9, 10, 13) or 0x20 <= n <= 0xD7FF
or 0xE000 <= n <= 0xFFFD or 0x10000 <= n <= 0x10FFFF)
def serialize(record):
if not all(xml10_char(c) for value in record.values() for c in value):
raise ValueError('XML 1.0 forbidden character')
root = ET.Element('fixture')
for key, value in record.items():
ET.SubElement(root, key).text = value
return ET.tostring(root, encoding='utf-8', xml_declaration=True)
def decode(payload):
return {child.tag: child.text for child in ET.fromstring(payload)}
payload = serialize(approved)
assert decode(payload) == approved
assert b'&lang=fr' in payload
assert decode(payload)['url'].endswith('q=a%2Fb&lang=fr')
preescaped = dict(approved, title=html.escape(approved['title']))
assert decode(serialize(preescaped)) != approved
print('double-escaping negative detected')
try:
serialize(dict(approved, text='bad\u0000character'))
except ValueError:
print('forbidden-character negative detected')
else:
raise AssertionError('Forbidden XML character was accepted')
print('approved text and URL round-trip PASS')The expected output detects double escaping, rejects the forbidden control and passes the approved text-and-URL round-trip. The serializer receives plain approved strings. Pre-escaping a title before assigning it as text changes the parsed value, which is why the negative is not accepted merely because it remains well formed.
The explicit character check rejects an input the publisher has no approved XML representation for. Do not silently strip the character and claim complete fidelity. Record the affected source and let the editor or import owner approve a correction. This guard is specific to the fixture’s XML 1.0 character range, not a general text-sanitization service.
Verify the real feed and sitemap producers
Apply equivalent preservation assertions to the actual source fields the publisher emits. RSS title text, RSS description content and a sitemap loc can have different format contracts. If a description intentionally contains HTML, decide whether the feed contract carries encoded markup as text before writing its independent expected value.
Use the actual namespaces when selecting elements from a sitemap or Atom feed. A parser returning no entries because the query ignored a namespace is an observation-tool defect, not proof the feed was empty. Check expected item counts and identities separately from character preservation.
For a growing sitemap, pair this check with the partition coverage test. Correct escaping cannot restore a URL omitted from every partition. Conversely, a complete URL count does not reveal an ampersand converted into the wrong destination.
Fetch the delivered XML after release and parse that response, rather than only examining an intermediate string in a unit test. Preserve response status, format, bytes or digest, source revision and the independently approved fields used for comparison.
Keep identity and chronology outside the escape repair
Do not regenerate GUIDs, invent publication times or advance sitemap modification dates merely because the serializer was corrected. Use the content change record to preserve what changed and distinguish a transport repair from an editorial revision.
Accept when the delivered XML parses, the required fields decode to their approved values and both deliberate negatives still fail as intended. Subscriber behavior and search-engine processing remain separate observations. A valid feed communicates the publication coherently; it does not guarantee discovery or indexing.
