XML 服务器
服务器上的 XML
Section titled “服务器上的 XML”XML 文件是纯文本文件,可以很容易地存储在标准 Web 服务器上并由其提供服务。服务器端应用程序也可以动态生成 XML。
存储静态 XML 文件
Section titled “存储静态 XML 文件”您可以像存储 .html 或 .css 文件一样将 .xml 文件存储在 Web 服务器上。创建一个名为 note.xml 的文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?><note> <from>Jani</from> <to>Tove</to> <message>Remember me this weekend</message></note>将此文件放置在您的 Web 服务器文档根目录或子目录中。当浏览器请求此文件时,服务器通常会发送一个 Content-Type 头部为 application/xml 或 text/xml 的响应,以便浏览器将其识别为 XML。
动态生成 XML(Node.js 示例)
Section titled “动态生成 XML(Node.js 示例)”服务器端应用程序经常需要根据数据库或其他来源的数据生成 XML。以下是使用 Node.js 和流行的 xmlbuilder2 库的示例:
首先,安装该库:npm install xmlbuilder2
然后,创建一个简单的 Web 服务器(例如,使用 Node 的内置 http 模块)来生成 XML:
const http = require('http');const { create } = require('xmlbuilder2');
const server = http.createServer((req, res) => { if (req.url === '/dynamic-note.xml') { // Data that might come from a database or calculation const noteData = { to: 'Tove', from: 'Jani', message: 'Remember me this weekend (Dynamically generated!)', timestamp: new Date().toISOString() };
// Create the XML structure const root = create({ version: '1.0', encoding: 'UTF-8' }) .ele('note', { priority: 'normal' }) .ele('to').txt(noteData.to).up() .ele('from').txt(noteData.from).up() .ele('message').txt(noteData.message).up() .ele('timestamp').txt(noteData.timestamp).up() .up();
// Convert the XML object to a string const xmlString = root.end({ prettyPrint: true });
// Send the response res.writeHead(200, { 'Content-Type': 'application/xml' }); res.end(xmlString); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); }});
const PORT = 3000;server.listen(PORT, () => { console.log(`Server listening on http://localhost:${PORT}`);});当您访问 http://localhost:3000/dynamic-note.xml 时,服务器将生成并返回 XML。注意 Content-Type 头部是如何设置为 application/xml 的。
其他后端语言也有类似的方法,例如 Python(使用 xml.etree.ElementTree)、PHP(使用 DOMDocument 或 XMLWriter)、Java(使用 JAXB/Jakarta XML Binding)、C#、Ruby 等。
从数据库生成 XML(概念性 Node.js 示例)
Section titled “从数据库生成 XML(概念性 Node.js 示例)”一种常见的用例是从数据库查询结果中生成 XML。以下是一个使用 Node.js 和假设的数据库客户端(如用于 PostgreSQL 的 pg 或用于 MySQL 的 mysql2)的概念性示例:
const http = require('http');const { create } = require('xmlbuilder2');// Assume 'dbClient' is a configured database client object// const dbClient = require('./db-config');
async function getGuestbookEntries() { // Placeholder for actual database query // const result = await dbClient.query('SELECT fname, lname FROM tblGuestBook ORDER BY entry_date DESC'); // return result.rows; return [ { fname: 'John', lname: 'Doe' }, { fname: 'Jane', lname: 'Smith' } ]; // Simulated data}
const server = http.createServer(async (req, res) => { if (req.url === '/guestbook.xml') { try { const entries = await getGuestbookEntries();
const root = create({ version: '1.0', encoding: 'UTF-8' }).ele('guestbook');
for (const entry of entries) { root.ele('guest') .ele('fname').txt(entry.fname).up() .ele('lname').txt(entry.lname).up() .up(); }
const xmlString = root.end({ prettyPrint: true });
res.writeHead(200, { 'Content-Type': 'application/xml' }); res.end(xmlString);
} catch (error) { console.error('Error generating guestbook XML:', error); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal Server Error'); } } else { // ... (handle other routes or 404) }});
// ... (server listen code)此示例获取数据(此处为模拟数据)并遍历它,创建一个表示留言簿条目的 XML 结构。
注意:Classic ASP 和使用 .mdb 文件的 ADO 是遗留技术,由于安全性和性能限制,不推荐用于新的开发。
在服务器上使用 XSLT 转换 XML(Node.js 示例)
Section titled “在服务器上使用 XSLT 转换 XML(Node.js 示例)”您可以在将结果(通常是 HTML)发送到客户端之前,在服务器上执行 XSLT 转换。如果您想确保一致的渲染,或者如果客户端不支持 XSLT,这会很有用。
使用 Node.js 和像 xslt-processor 这样的库:
首先,安装库:npm install xslt-processor xmldom
示例服务器代码:
const http = require('http');const fs = require('fs').promises;const { XSLTProcessor } = require('xslt-processor');const { DOMParser, XMLSerializer } = require('xmldom');
const server = http.createServer(async (req, res) => { if (req.url === '/transformed-data') { try { // Load XML and XSL files (adjust paths as needed) const xmlString = await fs.readFile('data.xml', 'utf8'); const xslString = await fs.readFile('transform.xsl', 'utf8');
// Parse XML and XSL const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'application/xml'); const xslDoc = parser.parseFromString(xslString, 'application/xml');
// Perform the transformation const processor = new XSLTProcessor(); processor.importStylesheet(xslDoc); const resultDocument = processor.transformToDocument(xmlDoc);
// Serialize the result (often HTML) const serializer = new XMLSerializer(); const resultString = serializer.serializeToString(resultDocument);
// Send the transformed content (assuming HTML output) res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(resultString);
} catch (error) { console.error('Error during XSLT transformation:', error); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal Server Error'); } } else { // ... (handle other routes or 404) }});
// ... (server listen code)此代码读取 XML 文件(data.xml)和 XSL 文件(transform.xsl),使用 xslt-processor 执行转换,并将结果 HTML(或其他格式)发送到客户端。
注意:原始 ASP 示例中使用的 Microsoft.XMLDOM 对象是 Microsoft 旧服务器环境特有的,不具备可移植性。
将 XML 保存到文件(Node.js 示例)
Section titled “将 XML 保存到文件(Node.js 示例)”服务器端代码还可以生成 XML 并将其保存到服务器文件系统上的文件中。使用 Node.js 及其内置的 fs(文件系统)模块:
const fs = require('fs').promises; // Using the promise-based versionconst { create } = require('xmlbuilder2');
async function saveNoteToFile(filename) { const noteData = { to: 'Tove', from: 'Jani', heading: 'Reminder', body: "Don't forget me this weekend! (Saved from Node.js)" };
// Create XML structure const root = create({ version: '1.0', encoding: 'UTF-8' }) .ele('note') .ele('to').txt(noteData.to).up() .ele('from').txt(noteData.from).up() .ele('heading').txt(noteData.heading).up() .ele('body').txt(noteData.body).up() .up();
const xmlString = root.end({ prettyPrint: true });
try { await fs.writeFile(filename, xmlString, 'utf8'); console.log(`XML successfully saved to ${filename}`); } catch (error) { console.error(`Error saving XML to ${filename}:`, error); }}
// Example usage:saveNoteToFile('saved_note.xml');此函数生成一个 XML 字符串,并使用 fs.writeFile 将其异步保存到 saved_note.xml。