简体   繁体   English

Node.js:如何创建 XML 文件

[英]Node.js: How to create XML files

Is there a good way to create XML files?有没有创建 XML 文件的好方法? For example, like the Builder for Rails (or any other way)?例如,像 Builder for Rails (或任何其他方式)?

Thanks谢谢

It looks like the xmlbuilder-js library may do this for you.看起来xmlbuilder-js库可以为你做这件事。 If you have npm installed, you can npm install xmlbuilder .如果你安装了 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>

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

xmlbuilder was discontinued and replaced by xmlbuilder2 , which has been redesigned from the ground up to be fully conforming to the modern DOM specification . xmlbuilder已停产,取而代之的是xmlbuilder2 ,后者已xmlbuilder2开始重新设计以完全符合现代 DOM 规范

To install xmlbuilder2 using npm :要使用npm安装xmlbuilder2

npm install xmlbuilder2

An example, from their home page, for creating a new XML file with it:来自他们主页的一个示例,用于使用它创建一个新的 XML 文件:

const { create } = require('xmlbuilder2');

const root = create({ version: '1.0' })
  .ele('root', { att: 'val' })
    .ele('foo')
      .ele('bar').txt('foobar').up()
    .up()
    .ele('baz').up()
  .up();

// convert the XML tree to string
const xml = root.end({ prettyPrint: true });
console.log(xml);

Will result in:会导致:

<?xml version="1.0"?>
<root att="val">
  <foo>
    <bar>foobar</bar>
  </foo>
  <baz/>
</root>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM