Search code examples
node.jsparsingelementtreepretty-print

nodejs elementtree npm etree.write() pretty printing


I have ran into a problem while using the etree npm for nodejs. I am extensively using the elementtree npm in my application so I cannot afford to change the npm. I am writing the XML using the below code.

var et = require('elementtree');
tailorData = fs.readFileSync(XML_FILE).toString();
etree = et.parse(tailorData);
// Do some changes in xml
var resultXml = etree.write(); // DOES NOT DO PRETTY PRINTING
fs.writeFileSync(tailoredXML, resultXml);

etree.write() messed up the whole XML and my later processing is halted. It does not put endline after the tags. This is how the XML looks like now.

<?xml version='1.0' encoding='utf-8'?><Tailoring id="1234"><status>incomplete</status><Profile id="CIS_LEVEL_1"><title>CIS_LEVEL_1 Security Profile</title><select idref="file_group_owner_grub2_cfg" selected="true" /><select idref="file_user_owner_grub2_cfg" selected="true" /><select idref="file_permissions_grub2_cfg" selected="true" /></Profile></Tailoring>

Below is my expectation:

<?xml version='1.0' encoding='utf-8'?>
<Tailoring id="1234">
<status>incomplete</status>
<Profile id="CIS_LEVEL_1">
<title>CIS_LEVEL_1 Security Profile</title>
<select idref="file_group_owner_grub2_cfg" selected="true" />
<select idref="file_user_owner_grub2_cfg" selected="true" />
<select idref="file_permissions_grub2_cfg" selected="true" />
</Profile>
</Tailoring>

Is their any way I can acheive the above result in nodejs.


Solution

  • Figured out the way to do it. Using the very light weight npm "pretty-data" for achieving this.

    var pd = require('pretty-data').pd;
    
    var et = require('elementtree');
    tailorData = fs.readFileSync(XML_FILE).toString();
    etree = et.parse(tailorData);
    // Do some changes in xml
    var resultXml = etree.write();
    resultXml = pd.xml(resultXml); // THIS WILL DO THE PRETTY PRINTING.
    fs.writeFileSync(tailoredXML, resultXml);