在 TypeScript 中处理 XML:库概览与实践示例
XML(可扩展标记语言)仍然是企业系统、配置文件以及 Web 服务(SOAP、RSS/Atom)中用于数据交换的流行格式。在 TypeScript 中,得益于静态类型,处理 XML 变得更加安全和可预测。在本文中,我们将介绍三个用于在 TypeScript 中处理 XML 的主要库:fast-xml-parser、xml2js 和 xmlbuilder2。您将学习如何解析 XML、创建 XML 文档以及验证其结构。
1. 安装与配置
首先,通过 npm 安装一个或多个库:
npm install fast-xml-parser xml2js xmlbuilder2npm install -D @types/xml2js // xml2js 的类型定义(fast-xml-parser 内置类型)2. 使用 fast-xml-parser 解析 XML
fast-xml-parser 是 JavaScript/TypeScript 中解析 XML 最快的库。它支持属性、命名空间,并可以将 XML 转换为 JSON。
基本解析
import { XMLParser } from 'fast-xml-parser';
const xmlString = `<bookstore> <book category="fiction"> <title>战争与和平</title> <author>列夫·托尔斯泰</author> <price currency="RUB">1200</price> </book></bookstore>`;
const parser = new XMLParser({ ignoreAttributes: false, // 保留属性 attributeNamePrefix: '@_', // 属性前缀});
const result = parser.parse(xmlString);console.log(result);结果将是一个对象:
{ bookstore: { book: { '@_category': 'fiction', title: '战争与和平', author: '列夫·托尔斯泰', price: { '@_currency': 'RUB', '#text': '1200' } } }}带类型的解析
interface Book { '@_category': string; title: string; author: string; price: { '@_currency': string; '#text': number; };}
interface Bookstore { bookstore: { book: Book | Book[]; };}
const typedResult = parser.parse(xmlString) as Bookstore;console.log(typedResult.bookstore.book);3. 使用 xml2js 解析 XML
xml2js 是一个功能更强大的库,支持 process 函数和自定义转换。它异步工作。
异步解析
import { parseStringPromise } from 'xml2js';
interface XmlBook { $: { category: string }; title: string[]; author: string[]; price: Array<{ $: { currency: string }, _: string }>;}
async function parseXmlData(xml: string): Promise<void> { try { const result = await parseStringPromise(xml, { explicitArray: false, // 不将单个元素包装成数组 attrkey: '$', // 属性的键 charkey: '_' // 文本内容的键 }); const book = result.bookstore.book as XmlBook; console.log(`书籍:${book.title},作者:${book.author}`); console.log(`价格:${book.price._} ${book.price.$.currency}`); } catch (error) { console.error('XML 解析错误:', error); }}
parseXmlData(xmlString);4. 使用 xmlbuilder2 创建 XML
xmlbuilder2 是一个用于创建 XML 文档的现代库,支持 TypeScript。它提供链式 API 并自动进行转义。
创建简单的 XML
import { create } from 'xmlbuilder2';
const xml = create({ version: '1.0', encoding: 'UTF-8' }) .ele('catalog') .ele('book', { id: '1', category: 'fiction' }) .ele('title').txt('罪与罚').up() .ele('author').tx