Created
November 9, 2023 18:22
-
-
Save nathanclevenger/c0027c238144fe09dfecaea0b09aa83a to your computer and use it in GitHub Desktop.
FreeMind to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DOMParser = require('xmldom').DOMParser; | |
var fs = require('fs'); | |
var path = require('path'); | |
function convertBack(xml) { | |
const parser = new DOMParser(); | |
const xmlDoc = parser.parseFromString(xml, 'text/xml'); | |
const jsonOutput = {}; | |
const rootNode = xmlDoc.getElementsByTagName('node')[0]; | |
const jsonFileName = rootNode.getAttribute('TEXT'); | |
function recur(node, obj) { | |
let children = Array.from(node.childNodes).filter(n => n.nodeName === 'node'); | |
if (children.length > 0) { | |
children.forEach(child => { | |
const childKey = child.getAttribute('TEXT'); | |
if (child.childNodes.length === 1 && child.firstChild.nodeName === 'node') { | |
// Single child node case, direct value | |
obj[childKey] = child.firstChild.getAttribute('TEXT'); | |
} else { | |
// Multiple children, nested object or array | |
obj[childKey] = child.childNodes.length > 1 ? [] : {}; | |
recur(child, obj[childKey]); | |
} | |
}); | |
} else { | |
return; | |
} | |
} | |
// If the root has children, start the recursive process. | |
if (rootNode.childNodes.length > 0) { | |
jsonOutput[jsonFileName] = {}; | |
recur(rootNode, jsonOutput[jsonFileName]); | |
} | |
return JSON.stringify(jsonOutput, null, 2); // Returns pretty-printed JSON | |
} | |
function createJSONFromMindMap(sourceFilePath, targetFilePath) { | |
if (!fs.existsSync(sourceFilePath)) throw ('Error: XML file does not exist'); | |
const xmlInput = fs.readFileSync(sourceFilePath, 'utf8'); | |
const jsonOutputData = convertBack(xmlInput); | |
fs.writeFileSync(targetFilePath, jsonOutputData, { encoding: 'utf8' }); | |
} | |
module.exports = { | |
convertBack, | |
createJSONFromMindMap | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment