您的位置:首页 > Web前端 > Node.js

Node.js 使用xml2js处理xml

2018-01-25 18:45 441 查看
(Mac环境)

https://github.com/Leonidas-from-XIV/node-xml2js

Mac 没有ll命令
$vim ~/.bash_profile //编辑文件
I //插入
alias ll='ls -alF'  //取别名
wq //写入退出
$source ~/.bash_profile //使其生效,可以使用ll命令了


$npm install -g xml2js   // 安装xml2js全局模块


$npm ls -g  //查看全局模块安装依赖树


解决require("xml2js")全局模块找不到的问题:
$vim ~/.bash_profile
export NODE_PATH="/usr/local/lib/node_modules" //添加环境变量
$source ~/.bash_profile


Android资源文件strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="test1">aaa</string>
<string name="test2">bbb</string>
<string name="test3">ccc</string>
</resources>


test.js

var fs = require('fs');
var xml2js = require('xml2js');

var parser = new xml2js.Parser();
var filePath = "./strings.xml";

fs.readFile(filePath, function(err, data) {
parser.parseString(data, function (err, result) {
var strings = result.resources.string
for(var i=0;i< strings.length;i++ ){
console.log(strings[i].$.name)
console.log(strings[i]._)
}
});
});


attrkey (default: $): Prefix that is used to access the attributes. Version 0.1 default was @.

charkey (default: _): Prefix that is used to access the character content. Version 0.1 default was #.

详细用法可到上述github查看

运行结果

$node test.js
test1
aaa
test2
bbb
test3
ccc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Node xml2js js解析xml