mac电脑解压出来的xmind的数据主要在content.json上
开头结尾有[],里面是json
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;public class XMindLeafCounter2 {public static void main(String[] args) {String xmindFilePath = "path/to/your/file.xmind"; // 替换为你的XMind文件路径try {// 解压XMind文件并提取content.json内容String jsonContent1 = extractContentJson(xmindFilePath);//System.out.println(jsonContent1);String jsonContent = removeOuterBrackets(jsonContent1);// System.out.println(jsonContent);JSONObject jsonObject = new JSONObject(jsonContent);int leafNodeCount = 0;// 遍历每个sheetJSONObject rootTopic = jsonObject.getJSONObject("rootTopic");leafNodeCount += countLeafNodes(rootTopic);System.out.println("Total leaf nodes: " + leafNodeCount);} catch (IOException e) {e.printStackTrace();}}public static String removeOuterBrackets(String str) {if (str == null || str.length() <= 1) {return str; // 如果字符串为空或者长度小于等于1, 直接返回}// 使用substring去掉最外层的方括号if (str.startsWith("[") && str.endsWith("]")) {return str.substring(1, str.length() - 1);}return str; // 如果没有匹配上最外层的中括号,直接返回原字符串}/*** 从XMind文件中解压并提取content.json的内容** @param xmindFilePath XMind文件路径* @return content.json文件内容字符串* @throws IOException 如果解压或读取文件失败*/private static String extractContentJson(String xmindFilePath) throws IOException {File xmindFile = new File(xmindFilePath);try (ZipInputStream zis = new ZipInputStream(new FileInputStream(xmindFile))) {ZipEntry entry;while ((entry = zis.getNextEntry()) != null) {if (entry.getName().equals("content.json")) {ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length;while ((length = zis.read(buffer)) != -1) {outputStream.write(buffer, 0, length);}zis.closeEntry();return outputStream.toString("UTF-8");}}}throw new FileNotFoundException("content.json not found in the XMind file.");}/*** 递归计算叶子节点数** @param topic JSON对象表示的主题节点* @return 叶子节点数*/private static int countLeafNodes(JSONObject topic) {if (topic.has("children")) {JSONObject children = topic.getJSONObject("children");if (children.has("attached")) {JSONArray attached = children.getJSONArray("attached");int count = 0;for (int i = 0; i < attached.length(); i++) {JSONObject child = attached.getJSONObject(i);count += countLeafNodes(child);}return count;}}// 如果没有子节点,则为叶子节点return 1;}
}