如何将数据写入节点js中的xml文件

时间:2016-08-04 11:20:11

标签: xml node.js node-modules

我的xml文件

   <?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
      <title>XpertDox Home Page</title>
  <link>http://www.xpertdox.com</link>
    <description>Find a doctor</description>
<item>
<title>Xpertdox</title>
<link>http://www.xpertdox.com/rss.xml</link>
<description>Find an Xpert Doctor for an unknown Disease</description>
</item>

  I want  to  add this
    <item>
<title>Tony</title>
<link>startk</link>
<description>hi</description>
</item>

    

我的node.js

var obj = {title: "Tony", link: "Stark" , "description":"hi"};
var fs = require('fs');
var xml2js = require('xml2js');

var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);  

fs.writeFile('feed.xml', xml, function (err){
if (err) throw err;
    console.log('It\'s saved!');
}); 

我想替换我的obj中声明的标题标签和链接,但这不起作用。任何人都可以更改我的代码........

3 个答案:

答案 0 :(得分:1)

在谷歌的这篇文章中,我正在寻找一些略有不同的东西,但在这里,我的这段代码应该为遇到这篇文章的任何人解决这个问题。

function xmlFileToObject(path) {
    return new Promise((resolve,reject) => {
        getFile(path).then(xml => {
            parseXml(xml).then(result => {
                resolve(result);
            });
        });
    });
}
function getFile(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf8', function (err,data) {
            if (err) console.error(err);
            resolve(data);
        });
    });
}
function parseXml(xml) {
    return new Promise((resolve,reject) => {
        var parseString = require('xml2js').parseString;
        parseString(xml, function (err, result) {
            resolve(result);
        });
    });
}

答案 1 :(得分:1)

谢谢Shard。 更多E6惯例: `

const getFile = dir => new Promise((resolve, reject) => {
  fs.readFile(dir, 'utf8', (err, data) =>
    (err ? reject(err) : resolve(data)));
});

const parseXml = xml => new Promise((resolve, reject) => {
  require('xml2js').parseString(xml, (err, result) =>
    (err ? reject(err) : resolve(result)));
});

const xmlFileToObject = dir => getFile(dir)
  .then(xml => parseXml(xml))
  .then(result => console.log(result))
  .catch(e => console.error(e));

`

答案 2 :(得分:0)

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