以下は、JavaScriptでXMLを取得し、JSONファイルに変換するスクリプトの例です。
const xmlUrl = '<http://example.com/sample.xml>'; // XMLファイルのURL
const request = new XMLHttpRequest(); // XMLHttpRequestオブジェクトを作成
request.open('GET', xmlUrl, true); // リクエストを開く
// リクエストが完了した場合に呼び出される関数を定義
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// リクエストが成功した場合
const xmlString = request.responseText; // XMLデータを取得
const parser = new DOMParser(); // DOMParserオブジェクトを作成
const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // XMLデータを解析
const jsonData = xmlToJson(xmlDoc); // XMLをJSONに変換
// JSONデータをダウンロードする
const jsonBlob = new Blob([JSON.stringify(jsonData)], { type: 'application/json' });
const jsonUrl = URL.createObjectURL(jsonBlob);
const a = document.createElement('a');
a.href = jsonUrl;
a.download = 'data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
// リクエストが失敗した場合
console.log('XMLデータの取得に失敗しました。');
}
};
// リクエストがエラーの場合に呼び出される関数を定義
request.onerror = function() {
console.log('XMLデータの取得に失敗しました。');
};
// リクエストを送信する
request.send();
// XMLをJSONに変換する関数
function xmlToJson(xml) {
// XML要素がテキストノードしか持たない場合に、テキストノードの値を取得する
function extractValue(node) {
return node.childNodes.length === 1 ? node.childNodes[0].nodeValue : null;
}
// XML要素をJSONオブジェクトに変換する
function convertToJson(node) {
const obj = {};
// 属性をJSONオブジェクトに変換する
if (node.attributes && node.attributes.length > 0) {
for (let i = 0; i < node.attributes.length; i++) {
const attribute = node.attributes[i];
obj[attribute.nodeName] = attribute.nodeValue;
}
}
// 子要素をJSONオブジェクトに変換する
if (node.childNodes && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
if (child.nodeType === 1) {
// 子要素が要素ノードの場合
const nodeName = child.nodeName;
if (obj[nodeName] === undefined) {
obj[nodeName] = convertToJson(child);
} else {
if (Array.isArray(obj[nodeName])) {
obj[nodeName].push(convertToJson(child));
} else {
obj[nodeName] =
`
ご指摘ありがとうございます。以下は、fetch APIを使用してJSONファイルをダウンロードするスクリプトの例です。
const xmlUrl = '<http://example.com/sample.xml>'; // XMLファイルのURL
fetch(xmlUrl)
.then(response => response.text()) // レスポンスをテキストとして取得する
.then(xmlString => {
const parser = new DOMParser(); // DOMParserオブジェクトを作成
const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // XMLデータを解析
const jsonData = xmlToJson(xmlDoc); // XMLをJSONに変換
// JSONデータをダウンロードする
const jsonBlob = new Blob([JSON.stringify(jsonData)], { type: 'application/json' });
const jsonUrl = URL.createObjectURL(jsonBlob);
const a = document.createElement('a');
a.href = jsonUrl;
a.download = 'data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch(error => {
console.log('XMLデータの取得に失敗しました。', error);
});
// XMLをJSONに変換する関数
function xmlToJson(xml) {
// XML要素がテキストノードしか持たない場合に、テキストノードの値を取得する
function extractValue(node) {
return node.childNodes.length === 1 ? node.childNodes[0].nodeValue : null;
}
// XML要素をJSONオブジェクトに変換する
function convertToJson(node) {
const obj = {};
// 属性をJSONオブジェクトに変換する
if (node.attributes && node.attributes.length > 0) {
for (let i = 0; i < node.attributes.length; i++) {
const attribute = node.attributes[i];
obj[attribute.nodeName] = attribute.nodeValue;
}
}
// 子要素をJSONオブジェクトに変換する
if (node.childNodes && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
if (child.nodeType === 1) {
// 子要素が要素ノードの場合
const nodeName = child.nodeName;
if (obj[nodeName] === undefined) {
obj[nodeName] = convertToJson(child);
} else {
if (Array.isArray(obj[nodeName])) {
obj[nodeName].push(convertToJson(child));
} else {
obj[nodeName] = [obj[nodeName], convertToJson(child)];
}
}
} else if (child.nodeType === 3 || child.nodeType === 4) {
// 子要素がテキストノードまたはCDATAセクションの場合
const value = extractValue(child);
if (value !== null) {
if (obj.text === undefined) {
obj.text = value;
} else {
if (Array.isArray(obj.text)) {
obj.text.push(value);
} else {
obj.text = [obj.text, value];
}
}
}
}
}
}
return obj;
}
return convertToJson(xml.documentElement);
}
fetch APIを使用する場合、fetch関数を使用してXMLファイルを取得し、レスポンスをtext形式で取得します。次に、取得したXMLデータをDOMParserを使用して解析し、XMLをJSONに変換するxmlToJson関数を呼び出します。xmlToJson関数は、再帰的にXML要素をJSONオブジェクトに変換します。
最後に、JSONデータをダウンロードします。Blobオブジェクトを使用してJSON文字列をBlobに変換し、URL.createObjectURL関数を使用してBlobオブジェクトのURLを生成します。ダウンロードリンクを作成し、a要素のclickメソッドを呼び出してダウンロードを開始します。ダウンロードが完了したら、a要素を削除します。
Pythonでは、XMLをJSONに変換するための多数のライブラリが利用できます。以下は、xmltodictライブラリを使用した例です。
import xmltodict
import requests
xml_url = '<http://example.com/sample.xml>' # XMLファイルのURL
response = requests.get(xml_url) # XMLデータを取得する
if response.ok:
xml_data = response.content # レスポンスの内容を取得する
json_data = xmltodict.parse(xml_data) # XMLをJSONに変換する
with open('data.json', 'w') as f: # JSONファイルに書き込む
json.dump(json_data, f, ensure_ascii=False, indent=4)
else:
print('XMLデータの取得に失敗しました。')
まず、requestsモジュールを使用してXMLデータを取得します。次に、xmltodict.parse関数を使用してXMLをJSONに変換します。変換されたJSONデータをファイルに書き込みます。json.dump関数を使用してJSONを書き込み、ensure_ascii=Falseオプションを指定して、日本語文字列がエスケープされないようにします。indent=4オプションを指定して、JSONデータを読みやすく整形します。取得に失敗した場合は、エラーメッセージを出力します。