2017-05-11 58 views
0

我在使用etree npm for nodejs時遇到了問題。我在我的應用程序中廣泛使用elementtree npm,所以我不能改變npm。我正在使用下面的代碼編寫XML。nodejs elementtree npm etree.write()漂亮的打印

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()搞砸了整個XML,後來我的處理就停止了。它不會在標籤之後放置結束符。這就是XML現在的樣子。

<?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> 

下面是我的期望:

<?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> 

是他們的任何方法可以讓我acheive上述結果的NodeJS。

回答

0

想通了辦法。使用非常輕的npm「漂亮數據」來實現這一點。

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);