fast-xml-parser vs libxmljs vs libxmljs2 vs xml2js vs xmlbuilder vs xmldom
JavaScript における XML 処理ライブラリの選定ガイド
fast-xml-parserlibxmljslibxmljs2xml2jsxmlbuilderxmldom類似パッケージ:

JavaScript における XML 処理ライブラリの選定ガイド

これらのライブラリは、JavaScript 環境(Node.js およびブラウザ)で XML データの解析、検証、生成を行うためのツールです。実装アプローチは大きく分けて 2 つあります。一つは C 言語ライブラリ(libxml2)をネイティブバインディングで利用する方式、もう一つは純粋な JavaScript で実装された方式です。前者は機能面(XPath、XSD 検証など)で強力ですが環境依存があり、後者は移植性が高くセットアップが容易です。プロジェクトの要件(速度、セキュリティ、機能、デプロイ環境)に応じて適切な選択が必要です。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
fast-xml-parser03,0901.05 MB166日前MIT
libxmljs01,06017.7 MB693年前MIT
libxmljs2087.22 MB291年前MIT
xml2js04,9653.44 MB2463年前MIT
xmlbuilder0926-76年前MIT
xmldom0453-525年前MIT

JavaScript XML ライブラリ徹底比較:実装アーキテクチャと実用性

JavaScript で XML を扱う場合、目的によって選ぶべきライブラリが全く異なります。単にデータを読み込みたいだけなのか、複雑な検証が必要なのか、それとも XML を生成したいのか。ここでは 6 つの主要パッケージを、実装方式、API の使い勝手、機能、そして保守性の観点から比較します。

🏗️ 実装アーキテクチャ:ネイティブ依存 vs 純粋な JavaScript

ライブラリ選びで最初に確認すべきは、ネイティブコード(C 言語など)に依存しているかどうかです。これがデプロイの難易度と実行速度に直結します。

libxmljslibxmljs2 は、C 言語で書かれた高性能な XML ライブラリ「libxml2」を Node.js から呼び出すネイティブバインディングです。

  • 処理速度が非常に速く、XPath や XSD 検証など高機能です。
  • 一方で、環境ごとにネイティブモジュールのコンパイルが必要であり、サーバーレス環境やクロスコンパイルで問題が起きやすいです。
// libxmljs2: ネイティブモジュールの読み込みが必要
const libxmljs = require("libxmljs2");
const xmlDoc = libxmljs.parseXml(xmlString);

fast-xml-parserxml2jsxmldomxmlbuilder は、純粋な JavaScript で書かれています。

  • npm install するだけで動き、環境依存がありません。
  • ブラウザや AWS Lambda などの制限された環境でも動作します。
// fast-xml-parser: 追加ビルド不要でそのまま動作
const { XMLParser } = require("fast-xml-parser");
const parser = new XMLParser();
const result = parser.parse(xmlString);

📥 解析 API の使い勝手:コールバック vs 同期処理

非同期処理が主流の Node.js において、API が同期か非同期かはコードの書きやすさに影響します。

xml2js は伝統的にコールバックベースの API を採用しています。

  • Promise ラッパーを使わない限り、async/await との相性が悪く、コードがネストしがちです。
// xml2js: コールバックベース(Promise 化が必要)
const parseString = require('xml2js').parseString;
parseString(xml, (err, result) => {
  if (err) throw err;
  console.log(result);
});

fast-xml-parser は同期処理で結果を返します。

  • async/await の流れの中で自然に扱え、エラーハンドリングも try-catch で完結します。
// fast-xml-parser: 同期で結果が得られる
try {
  const result = parser.parse(xmlString);
  console.log(result);
} catch (e) {
  console.error(e);
}

libxmljs2 も同期処理を提供しますが、重い処理ではイベントループをブロックする可能性があります。

// libxmljs2: 同期パース
const doc = libxmljs.parseXml(xmlString);

xmldom はブラウザの DOM API に合わせた同期インターフェースを持ちます。

// xmldom: DOMParser を使用
const { DOMParser } = require('xmldom');
const doc = new DOMParser().parseFromString(xmlString, 'text/xml');

🔍 高度な機能:XPath とスキーマ検証

単なるパースを超えて、特定のノード検索や形式検証が必要かどうかで選択肢が絞られます。

libxmljs2 はこの分野で最強です。

  • XPath クエリによるノード検索や、XSD によるスキーマ検証がネイティブレベルでサポートされています。
// libxmljs2: XPath 検索と検証
const root = libxmljs.parseXml(xml);
const nodes = root.find('//book/title');
const isValid = root.validate(schemaDoc);

fast-xml-parser はバージョン 4 以降で簡易的な XPath 様の機能を持ちますが、完全な準拠ではありません。

  • 複雑なクエリには向きません。
// fast-xml-parser: 簡易的なアクセス(完全な XPath ではない)
// 基本的に JSON オブジェクトとしてアクセスするため、配列やオブジェクトを辿る
const title = result.library.book.title;

xml2jsxmldom は、XPath 機能を本体に含んでいません。

  • 別途 xpath などのライブラリを組み合わせる必要があります。
// xmldom + xpath: 別ライブラリとの組み合わせが必要
const xpath = require('xpath');
const nodes = xpath.select("//title", doc);

🛠️ XML 生成:専用ツールの有無

XML を解析するだけでなく、新しく作成する必要がある場合、xmlbuilder が役立ちます。

xmlbuilder は XML 生成に特化しています。

  • チェーンメソッドで直感的にツリー構造を構築できます。
// xmlbuilder: チェーンで構築
const builder = require('xmlbuilder');
const xml = builder.create('library')
  .ele('book').att('id', '123').ele('title').txt('JS Guide').up()
  .end({ pretty: true });

fast-xml-parser も JSON から XML への変換(Builder)機能を持っています。

  • 解析と生成を 1 つのライブラリで完結させたい場合に便利です。
// fast-xml-parser: JSON から XML へ変換
const { XMLBuilder } = require("fast-xml-parser");
const builder = new XMLBuilder();
const xmlContent = builder.build(jsonObject);

libxmljs2 でもノードを追加して生成できますが、コード量は多くなりがちです。

// libxmljs2: プログラムによるノード追加
const doc = new libxmljs.Document();
const root = doc.node('library');
const book = root.node('book').attr('id', '123');

🔒 セキュリティと保守状況:ここが最重要

オープンソースライブラリを選ぶ際、メンテナンス状況はセキュリティに直結します。

libxmljsxmldom(元パッケージ)は注意が必要です。

  • libxmljs は長期間更新が停滞しており、libxmljs2 への移行が公式に推奨されています。
  • xmldom もセキュリティ脆弱性の修正が停滞した時期があり、現在は @xmldom/xmldom への移行がアナウンスされています。
  • 新規プロジェクトでこれらを選択するのはリスクが高く、避けるべきです。

fast-xml-parserlibxmljs2 は現在アクティブにメンテナンスされています。

  • 脆弱性報告への対応が早く、Node.js の新バージョンにも追随しています。

📊 比較サマリー

機能fast-xml-parserlibxmljs2xml2jsxmlbuilderxmldom
実装純粋な JSネイティブ純粋な JS純粋な JS純粋な JS
解析速度⚡ 非常に速い⚡ 速い🐢 普通N/A🐢 普通
XPath 対応一部✅ 完全❌ (要追加)❌ (要追加)
XML 生成✅ 可能✅ 可能❌ (別版あり)✅ 特化
保守状況✅ アクティブ✅ アクティブ⚠️ 維持モード⚠️ 維持モード❌ 非推奨
環境依存なしあり (ビルド必要)なしなしなし

💡 結論:どのライブラリを選ぶべきか

プロジェクトの要件に応じて、以下のように選択するのが合理的です。

  1. モダンな Web アプリやサーバーレス環境

    • fast-xml-parser を選んでください。インストールが簡単で高速、かつ解析と生成の両方をカバーしています。最もバランスが良い選択肢です。
  2. 高度な検証や複雑なクエリが必要なエンタープライズシステム

    • libxmljs2 一択です。XSD 検証や XPath が必要な場合、純粋な JS ライブラリでは実装コストが高すぎます。ネイティブコンパイルの環境構築コストを許容できる場合に使用します。
  3. XML 生成が主目的の場合

    • xmlbuilder が適しています。ただし、解析も必要なら fast-xml-parser との併用、あるいは fast-xml-parser 単体での完結を検討します。
  4. 避けるべき選択肢

    • libxmljsxmldom(無印)は、セキュリティと保守性の観点から新規プロジェクトでは使用しないでください。既存システムで使われている場合は、移行計画を立てることを強く推奨します。

XML 処理はアプリケーションの堅牢性に直結する部分です。一時的な導入のしやすさだけでなく、長期的なメンテナンス性とセキュリティを最優先してライブラリを選定してください。

選び方: fast-xml-parser vs libxmljs vs libxmljs2 vs xml2js vs xmlbuilder vs xmldom

  • fast-xml-parser:

    純粋な JavaScript で実装されており、インストールが容易で動作が非常に高速です。XML を JSON に変換する処理や、その逆の変換が必要なモダンなプロジェクトに最適です。ネイティブ依存がないため、サーバーレス環境やブラウザでの利用にも適しています。

  • libxmljs:

    このパッケージは現在メンテナンスが停止しており、新規プロジェクトでの使用は推奨されません。セキュリティ修正や Node.js の新バージョンへの対応が期待できないため、代替案を検討すべきです。

  • libxmljs2:

    libxmljs のアクティブにメンテナンスされているフォーク版です。XPath クエリや XSD によるスキーマ検証など、高度な XML 機能が必要な場合に選択します。ただし、ネイティブコンパイルが必要なため、デプロイ環境でビルドツールチェーンが整っている必要があります。

  • xml2js:

    長年利用されている定番のライブラリで、XML を JavaScript オブジェクトに変換する実績があります。既存のレガシーシステムとの互換性を保つ場合や、シンプルな変換処理で十分な場合に有用です。ただし、純粋な JS 実装の中では処理速度で劣る場合があります。

  • xmlbuilder:

    XML 構造をプログラムで構築・生成することに特化したライブラリです。他のパーサーと組み合わせて利用されることが多く、複雑な XML ドキュメントをコード上で組み立てる必要がある場合に適しています。

  • xmldom:

    W3C DOM 仕様を JavaScript で実装したものですが、元のパッケージはセキュリティ問題やメンテナンスの観点から非推奨となっています。DOM API が必要な場合は、公式に推奨されているフォーク版(@xmldom/xmldom)の使用を検討してください。

fast-xml-parser のREADME

fast-xml-parser

NPM total downloads

Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback.

FXP logo
  • Validate XML data syntactically. Use detailed-xml-validator to verify business rules.
  • Parse XML to JS Objects and vice versa
  • Common JS, ESM, and browser compatible
  • Faster than any other pure JS implementation.

It can handle big files (tested up to 100mb). XML Entities, HTML entities, and DOCTYPE entites are supported. Unpaired tags (Eg <br> in HTML), stop nodes (Eg <script> in HTML) are supported. It can also preserve Order of tags in JS object

Flexible-XML-Parser is 2 times faster than this library and allows to deal with incomplete XML/HTML. Output is highly customizable. Build whatever you want. So if you're fine with some extra configuration then try it out.


Your Support, Our Motivation

Please join Discord community for pre release announcements and discussions. This will prevent us to release breaking changes.

Financial Support

Sponsor this project




This is a donation. No goods or services are expected in return. Any requests for refunds for those purposes will be rejected.

Users

more

The list of users are mostly published by Github or communicated directly. Feel free to contact if you find any information wrong.


More about this library

How to use

To use as package dependency $ npm install fast-xml-parser or $ yarn add fast-xml-parser

To use as system command $ npm install fast-xml-parser -g

To use it on a webpage include it from a CDN

Example

As CLI command

$ fxparser some.xml

In a node js project

const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");

const parser = new XMLParser();
let jObj = parser.parse(XMLdata);

const builder = new XMLBuilder();
const xmlContent = builder.build(jObj);

In a HTML page

<script src="path/to/fxp.min.js"></script>
:
<script>
  const parser = new fxparser.XMLParser();
  parser.parse(xmlContent);
</script>

Bundle size

Bundle NameSize
fxbuilder.min.js6.5K
fxparser.min.js20K
fxp.min.js26K
fxvalidator.min.js5.7K

Documents

v3v4 and v5v6
documents
  1. Getting Started
  2. XML Parser
  3. XML Builder
  4. XML Validator
  5. Entities
  6. HTML Document Parsing
  7. PI Tag processing
  8. Path Expression
  1. Getting Started

note:

  • Version 6 is released with version 4 for experimental use. Based on its demand, it'll be developed and the features can be different in final release.
  • Version 5 has the same functionalities as version 4.

Performance

negative means error

XML Parser

  • Y-axis: requests per second
  • X-axis: File size

XML Builder

* Y-axis: requests per second

Usage Trend

Usage Trend of fast-xml-parser

NPM Usage Trend of fast-xml-parser

Supporters

Contributors

This project exists thanks to all the people who contribute. [Contribute].

Backers from Open collective

Thank you to all our backers! 🙏 [Become a backer]

License

  • MIT License

Donate $5