TExcelTAD
Home › XML › XML Server

XML on the Server

XML is plain text, so any server-side language can produce it — no special software is needed. What makes a response "XML" for the client is simply that the body is well-formed XML and the HTTP header says so.

The Content-Type header

http
HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8

<?xml version="1.0" encoding="UTF-8"?>
<status><server>online</server><users>128</users></status>
Media type Used for
application/xml General XML (preferred)
text/xml General XML (older, still common)
application/rss+xml RSS feeds
application/atom+xml Atom feeds
image/svg+xml SVG images
application/xhtml+xml XHTML pages

If the header is wrong (for example text/plain), XMLHttpRequest.responseXML will be null and browsers won't show their XML tree view.

Static files

The easiest "XML server" is a static file. Put catalog.xml next to your HTML and every web server (Apache, Nginx, Vite, GitHub Pages …) will serve it with an XML content type based on the .xml extension.

Generating XML dynamically

When the data comes from a database, the server builds the XML for each request. The golden rule: use an XML library, don't concatenate strings. A library escapes <, & and quotes for you, so a product called Salt & Pepper can't break the document.

Python's standard library makes this easy:

python · try it yourself
import xml.etree.ElementTree as ET

products = [("Salt & Pepper set", 8.5), ("Olive oil <1L>", 12.0)]

root = ET.Element("products")
for name, price in products:
    p = ET.SubElement(root, "product", price=f"{price:.2f}")
    p.text = name

ET.indent(root)
print(ET.tostring(root, encoding="unicode"))
<products>
  <product price="8.50">Salt &amp; Pepper set</product>
  <product price="12.00">Olive oil &lt;1L&gt;</product>
</products>

The same idea in other server languages:

Node.js (Express) — build with a library such as xmlbuilder2, or the DOM from @xmldom/xmldom:

js
import express from 'express';
import { create } from 'xmlbuilder2';

const app = express();
app.get('/api/status.xml', (req, res) => {
  const xml = create({ version: '1.0', encoding: 'UTF-8' })
    .ele('status')
      .ele('server').txt('online').up()
      .ele('users').txt(String(128)).up()
    .end({ prettyPrint: true });
  res.type('application/xml').send(xml);
});
app.listen(3000);

PHP — the built-in SimpleXMLElement class:

php
<?php
header('Content-Type: application/xml; charset=utf-8');
$xml = new SimpleXMLElement('<status/>');
$xml->addChild('server', 'online');
$xml->addChild('users', '128');
echo $xml->asXML();

C# / ASP.NET — LINQ to XML:

csharp
var doc = new XDocument(
    new XElement("status",
        new XElement("server", "online"),
        new XElement("users", 128)));
return Content(doc.ToString(), "application/xml");

Building XML in the browser

The browser has the same tools: create a DOM and serialise it. This is handy for exporting data from a web app as an .xml download:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const products = [['Salt & Pepper set', 8.5], ['Olive oil <1L>', 12]];

    const doc = document.implementation.createDocument(null, 'products');
    for (const [name, price] of products) {
      const p = doc.createElement('product');
      p.setAttribute('price', price.toFixed(2));
      p.textContent = name;                 // escaping happens automatically
      doc.documentElement.append(p);
    }
    console.log(new XMLSerializer().serializeToString(doc));
  </script>
</body>
</html>

Reading XML on the server

Servers also receive XML — SOAP web services, payment notifications, file uploads. Two security rules matter:

  1. Disable external entities and DTD processing for untrusted input (to stop XXE and "billion laughs" attacks). Many libraries are safe by default now, but check: in Python prefer defusedxml; in Java set XMLConstants.FEATURE_SECURE_PROCESSING and disallow DOCTYPE declarations.
  2. Validate against a schema before trusting the content.

Tip: SOAP, the XML messaging protocol behind many enterprise and government web services, is just XML sent over HTTP POST with the type application/soap+xml. Everything in this course applies to reading it.

Test yourself

Which HTTP header tells the client that a response is XML?

  1. Accept: xml
  2. Content-Type: application/xml
  3. X-Format: XML
  4. Content-Encoding: xml

Why should servers build XML with a library instead of string concatenation?

  1. Libraries make the file smaller
  2. Libraries escape special characters like & and < correctly
  3. String concatenation is not allowed in PHP
  4. Browsers only accept library-generated XML