0
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?

More than 1 year has passed since last update.

Next.jsでのxml2jsの使い方

Last updated at Posted at 2023-08-29

xml形式のレスポンスをNextで処理するためのパッケージとしてxml2jsがあります。Nextで使用する例がなかなか見つからず苦労したのでNextで使用する方法を紹介します。

インストール

まず、以下のコマンドでxml2jsをインストールします。

npm i xml2js

次に、xml2jsを使用しますが、今回はNextのAppRouterを使用すること及びuseEffect内でAPIにリクエストを送信しxml形式のレスポンスを処理することを想定します。この場合は以下のようなコードとなります。

'use client';
・
・
・
import { useEffect, useState } from 'react';
import { parseString } from 'xml2js';
・
・
・
interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}
・
・
・
const [articles, setArticles] = useState<Article[]>([]);
・
・
・
useEffect(() => {
    async function fetchData() {
      const url = API_URL; //API_URLを任意のものに変更してください。
      try {
        const response = await axios.get(url);
        console.log(response);
        const xmlData = response.data;
        parseString(xmlData, (err, result) => {
          if (err) {
            console.error('XMLの解析エラー:', err);
          } else {
            const parsedArticles = XML_RESPONSE //レスポンスの構造に応じてXML_RESPONSEを変更してください。
            setArticles(parsedArticles);
             }
        });
      } catch (error) {
        console.error('データの取得エラー:', error);
      }
    }
    fetchData();
  }, []);
・
・
・
0
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
0
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?