2011-09-02 31 views

Trả lời

40

Có vẻ như thư viện xmlbuilder-js có thể làm điều này cho bạn. Nếu bạn đã cài đặt npm, bạn có thể npm install xmlbuilder.

Nó sẽ cho phép bạn làm điều này (lấy từ tấm gương của họ):

var builder = require('xmlbuilder'); 
var doc = builder.create(); 

doc.begin('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'); 

console.log(doc.toString({ pretty: true })); 

mà sẽ cho kết quả:

<root> 
    <xmlbuilder for="node-js"> 
    <repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo> 
    </xmlbuilder> 
    <test>complete</test> 
</root> 
+1

rất hữu ích. thanx – j03m

+1

Tôi đang gặp vấn đề nhỏ với vấn đề này. Tôi đăng trên [github] (https://github.com/oozcitak/xmlbuilder-js/issues/23) nếu bạn quan tâm đến việc cho mượn một tay. – ThomasReggi

+0

Cảm ơn câu trả lời, ở đây tôi tìm thấy một hướng dẫn về chủ đề này, tôi hy vọng nó sẽ hữu ích cho một ai đó. https://programmerblog.net/generate-xml-with-nodejs-and-mysql/ –

2

thay đổi gần đây xmlbuilder yêu cầu tên phần tử gốc truyền cho create()

xem ví dụ làm việc

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