將xml處理為json對象數組
阿新 • • 發佈:2017-11-10
lac XML match return function str == new for
function xmlStr2js(xmlStr) {
var tagNames = xmlStr.match(/<\w+>/g)
tagNames = deWeightTagNames(tagNames)
var jsonObj = new Object()
tagNames.forEach(function(tn) {
var _tn = tn.slice(1, -1)
var tnlen = tn.length
var reg = new RegExp("(" + tn + "((?!" + tn.replace(‘<‘, ‘<\/‘) + ").)*" + tn.replace(‘<‘, ‘<\/‘) + "|" + tn.replace(‘>‘, ‘/>‘) + ")", "g")
var fullTag = xmlStr.match(reg)
var valueArr = fullTag ? fullTag.map(function(ft) {
return ft.slice(-2) === "/>" ? "" : ft.slice(tnlen, -(tnlen + 1))
}) : null
jsonObj[_tn] = valueArr
})
return jsonObj }
function deWeightTagNames(tagNames) { var len = tagNames.length var _tns = [] for (var i = 0; i < len; i++) { _tns.indexOf(tagNames[i]) === -1 && _tns.push(tagNames[i]) } return _tns }
return jsonObj }
function deWeightTagNames(tagNames) { var len = tagNames.length var _tns = [] for (var i = 0; i < len; i++) { _tns.indexOf(tagNames[i]) === -1 && _tns.push(tagNames[i]) } return _tns }
將xml處理為json對象數組