我有一个不包含"LF"的文件主题.xml请参阅 https://en.wikipedia.org/wiki/Newline。但是在转换为 js 并返回 xml 后,我的结果包含"LF"换行符。这是一个问题,因为 Adobe Acrobat 8 标准要求一行中的 xml 文件作为头模板文件。听一个例子:
<?xml version = "1.0" encoding = "UTF-8" ?><HeaderFooterSettings version = "8.0"><Font name="Arial" size="11.0"/><Color b="0.0" r="0.0" g="0.0"/><Margin top="34.0159" left="72.0002" right="72.0002" bottom="36.0001"/><Appearance shrink="1" fixedprint="0"/><PageRange end="-1" start="-1" even="1" odd="1"/><Page offset = "0"><PageIndex format="1"/></Page><Date><Month format="1"/>/<Day format="1"/><Year format="0"/></Date><Header><Left>hello</Left><Center></Center><Right>world</Right></Header><Footer><Left></Left><Center></Center><Right></Right></Footer></HeaderFooterSettings>
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
xmlFileToJs('theme.xml', function (err, obj) {
if (err) throw (err);
jsToXmlFile('theme2.xml', obj, function (err) {
if (err) console.log(err);
})
});
function xmlFileToJs(filename, cb) {
var filepath = path.normalize(path.join(__dirname, filename));
fs.readFile(filepath, 'utf8', function (err, xmlStr) {
if (err) throw (err);
xml2js.parseString(xmlStr, {}, cb);
});
}
function jsToXmlFile(filename, obj, cb) {
var filepath = path.normalize(path.join(__dirname, filename));
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
fs.writeFile(filepath, xml, cb);
}
不幸的是,线路制动器"LF"的结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<HeaderFooterSettings version="8.0">
<Font name="Arial" size="11.0"/>
<Color b="0.0" r="0.0" g="0.0"/>
<Margin top="34.0159" left="72.0002" right="72.0002" bottom="36.0001"/>
<Appearance shrink="1" fixedprint="0"/>
<PageRange end="-1" start="-1" even="1" odd="1"/>
<Page offset="0">
<PageIndex format="1"/>
</Page>
<Date>
/
<Month format="1"/>
<Day format="1"/>
<Year format="0"/>
</Date>
<Header>
<Left>hello</Left>
<Center/>
<Right>world</Right>
</Header>
<Footer>
<Left/>
<Center/>
<Right/>
</Footer>
</HeaderFooterSettings>
我尝试了很多。 瞬间,但无法通过以下命令找到解决方案:
const stringify = require('xml-stringify');
var xmlc = require('xml');
const trimNewlines = require('trim-newlines');
xmlc(trimNewlines(JSON.stringify(obj)));
我也试过这个:
var builder = new xml2js.Builder({'trim' : true, 'normalize' : true});
好吧,没有机会。
我期待其他想法。
现在您可以使用
const builder = new xml2js.Builder({ renderOpts: { pretty: false } });
function onelinexml (xml) {
var pos = xml.search(" <");
var xmlstr = xml.replace(/n| | /g, "");
console.log('pos=%d',pos);
while (pos>=0){
var xmlstr = xmlstr.replace(/n| | /g, "");
var xmlstr = xmlstr.replace(/> /g, ">");
var xmlstr = xmlstr.replace(/ </g, "<");
pos = xmlstr.search(" <");
console.log('pos=%d',pos);
}
return xmlstr;
}
解决了。 谢谢。