1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSでXMLを整形+ハイライトで表示させる

Last updated at Posted at 2025-09-07

1.要件

XMLを文字列で取得したものを整形+ハイライトする方法を調査しました。

(1)XMLを整形する → XMLParser、XMLBuilder

XMLParser: XML文字列をJavaScriptのオブジェクトに変換するクラスです。
XMLBuilder: JavaScriptのオブジェクトをXML文字列に変換するクラスです。

(2)XMLをハイライトする → hljs、xmlLang

XMLParser: highlight.jsライブラリ全体の主要なオブジェクトです。
xmlLang: XML言語の構文ルールを定義したモジュールです。

2.XMLを整形してハイライト

JSの変換部分だけ記載します。

<script type="module">
    import { XMLParser, XMLBuilder } from 'https://cdn.jsdelivr.net/npm/fast-xml-parser@5.2.5/+esm';
    import hljs from "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/es/highlight.min.js";
    import xmlLang from "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/es/languages/xml.min.js";

    // 言語を確実に登録
    hljs.registerLanguage("xml", xmlLang);

    const $in = document.querySelector('#xml-in');
    const $out = document.querySelector('#xml-out');
    const $status = document.querySelector('#status');

    // XMLParserの利用時に設定を追加
    const parser = new XMLParser({
      ignoreAttributes: false,
      attributeNamePrefix: '@_',
      parseTagValue: false,
      parseAttributeValue: false,
      allowBooleanAttributes: true,
      trimValues: true
    });
    // XMLBuilderの利用時に設定を追加
    const builder = new XMLBuilder({
      ignoreAttributes: false,
      attributeNamePrefix: '@_',
      format: true,
      indentBy: '  ', // スペース2つに変更
      suppressEmptyNode: false
    });

    document.querySelector('#format-btn').addEventListener('click', () => {
      $status.textContent = '';
      const xml = ($in.value || '').trim();
      if (!xml)
      {
        $out.textContent = '';
        return;
    }
      
    try 
    {
        const obj = parser.parse(xml);
        const pretty = builder.build(obj);
        
        // 出力エリアにテキストとして設定
        $out.textContent = pretty;
        
        // highlight.js でシンタックスハイライト
        hljs.highlightElement($out);
        
        $status.textContent = '整形&ハイライトしました。';
    }
    catch (err) 
    {
        console.error(err);
        $status.textContent = '整形中にエラーが発生しました。';
    }
    });
    </script>

3.出力結果

例:

<?xml version="1.0" encoding="UTF-8"?><commerce_data><customer id="CUST-001"><personal_info><first_name>John</first_name><last_name>Doe</last_name><email>john.doe@example.com</email></personal_info><address type="shipping"><street>123 Main Street</street><city>Anytown</city><state>CA</state><zip_code>12345</zip_code><country>USA</country></address><address type="billing"><street>456 Oak Avenue</street><city>Sometown</city><state>NY</state><zip_code>67890</zip_code><country>USA</country></address></customer><order order_id="ORD-001" date="2024-09-07"><customer_ref id="CUST-001"/><items><item item_id="ITEM-A" quantity="2"><product_name>Wireless Mouse</product_name><price>25.50</price></item><item item_id="ITEM-B" quantity="1"><product_name>Mechanical Keyboard</product_name><price>89.99</price></item></items><shipping_info><method>Standard</method><fee>5.00</fee></shipping_info><total_amount>145.99</total_amount><notes>Please handle with care. This is a gift.</notes></order><order order_id="ORD-002" date="2024-09-06"><customer_ref id="CUST-002"/><items><item item_id="ITEM-C" quantity="3"><product_name>USB-C Cable</product_name><price>12.00</price></item></items><shipping_info><method>Express</method><fee>12.50</fee></shipping_info><total_amount>48.50</total_amount></order></commerce_data>

上記のXMLの文字列を設定して、#2の内容で出力した例です。
スクリーンショット 2025-09-07 22.47.46.png

→文字列で設定したXMLの内容が整形されてハイライトされ出力されます。

4.コード全容

以下のGitHubをご確認ください。
https://github.com/Fukuta-Y/Quita_example/blob/master/xml-formatter.html

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?