Javascript Node.js:如何创建 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7285393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: How to create XML files
提问by donald
Is there a good way to create XML files? For example, like the Builder for Rails (or any other way)?
有没有一种创建 XML 文件的好方法?例如,像 Builder for Rails(或任何其他方式)?
Thanks
谢谢
回答by Dylan Markow
It looks like the xmlbuilder-jslibrary may do this for you. If you have npm installed, you can npm install xmlbuilder
.
看起来xmlbuilder-js库可以为你做这件事。如果你安装了 npm,你可以npm install xmlbuilder
.
It will let you do this (taken from their example):
它会让你这样做(取自他们的例子):
var builder = require('xmlbuilder');
var doc = builder.create('root');
doc.ele('xmlbuilder')
.att('for', 'node-js')
.ele('repo')
.att('type', 'git')
.txt('git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('test')
.txt('complete');
console.log(doc.toString({ pretty: true }));
which will result in:
这将导致:
<root>
<xmlbuilder for="node-js">
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<test>complete</test>
</root>
回答by user3218782
recent changes to xmlbuilder require root element name passed to create()
最近对 xmlbuilder 的更改需要将根元素名称传递给 create()
see working example
参见工作示例
var builder = require('xmlbuilder');
var doc = builder.create('root')
.ele('xmlbuilder')
.att('for', 'node-js')
.ele('repo')
.att('type', 'git')
.txt('git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('test')
.txt('complete')
.end({ pretty: true });
console.log(doc.toString());