Node.js 使用xml2js处理xml

(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值