XML 脚本运行以打印所需的输出

问题描述 投票:0回答:1
javascript recursion linked-list scripting binary-search-tree
1个回答
0
投票

找到了使用不同 xml 解析器包的解决方案。

const fs = require('fs');
const sax = require('sax');

// Create a SAX parser
const parser = sax.parser(true);

// Create a write stream to a text file
const outputStream = fs.createWriteStream('output.txt');

// Array to store file attributes
let fileAttributes = [];

// Event handlers for the SAX parser
parser.onopentag = function (node) {
    // Check if the current node is a <file> element
    if (node.name === 'file') {
        // Extract attributes and push them to the array
        fileAttributes.push(node.attributes);
    }
};

parser.onend = function () {
    // Parsing ends, log the final output
    //console.log('File attributes:', fileAttributes);
    // Function to determine the file extension
function getFileExtension(currentLevel, nextLevel) {
    if (currentLevel < nextLevel) {
        return '.ditamap';
    } else {
        return '.dita';
    }
}

// Iterate through the fileAttributes array
for (let i = 0; i < fileAttributes.length; i++) {
    const currentFile = fileAttributes[i];
    const nextFile = fileAttributes[i + 1];

    // Get the level numbers
    const currentLevel = parseInt(currentFile.level.match(/\d+/)[0]);
    const nextLevel = nextFile ? parseInt(nextFile.level.match(/\d+/)[0]) : 0;

    // Get the file extension
    const extension = getFileExtension(currentLevel, nextLevel);

    // Indentation based on the level
    const indentation = ' '.repeat((currentLevel - 1) * 4);

    // Prepare the text to write
    const textToWrite = indentation + currentFile.heading + extension + '\n';

    // Write the text to the output stream
    outputStream.write(textToWrite);
}
// Close the output stream when done
outputStream.end();
};

// Read XML file
const xmlData = fs.readFileSync('input.xml', 'utf8');

// Parse XML data
parser.write(xmlData).close();

结果输出:

L1.ditamap
    L2.ditamap
        L3.dita
        L3.dita
        L3.dita
L1.dita
L1.ditamap
    L2.dita
    L2.ditamap
        L3.ditamap
            L4.ditamap
                Level5Text.dita
© www.soinside.com 2019 - 2024. All rights reserved.