JS:将xml数据转换为点数组表示法

时间:2019-09-11 20:18:33

标签: javascript xml multidimensional-array xml-parsing nested

我有一个xml文件,它是产品列表,并重复其本身以表示产品数量。 我的问题是我想将xml标签转换为点表示法javascript数组。

示例xml数据:http://a.cdn.searchspring.net/help/feeds/searchspring.xml

预期结果:

[ 
  'Products.Product.Product_ID',
  'Products.Product.SKU',
  'Products.Product.Name' 
]

在此示例xml中,访问产品名称的数据需要2个嵌套级别。但是,如果xml数据具有5个嵌套级别,则它必须最多读取5个嵌套级别。因此,它应取决于xml嵌套级别。 5个嵌套级xml数据的预期结果

[ 
  'Products.Product.Categories.Category.Name',
  'Products.Product.Categories.Category.Description',
]
import * as parser from 'fast-xml-parser';
import * as fs from 'fs';
import * as path from 'path';

const xmlData = fs.readFileSync(path.resolve('format.xml'), 'utf8');
const tObj = parser.getTraversalObj(xmlData);
const jsonObjects = parser.convertToJson(tObj);

function walk(obj, key = '', response = []) {
  Object.keys(obj).forEach(objKey => {
    key = key + objKey;
    if (!response.includes(key)) {
      response.push(key);
    }
    if (Object.keys(obj[objKey]).length > 0) {
      walk(obj[objKey], key, response);
    }
  });
  return response;
}

walk(jsonObjects);

当我尝试运行此代码时,出现“ RangeError:超出了最大调用堆栈大小”

1 个答案:

答案 0 :(得分:0)

我首先要检查一个嵌套对象,如果没有嵌套对象,请按实际键。

function walk(obj, key = '', response = []) {
    Object.keys(obj).forEach(objKey => {
        var newKey = key + (key && '.') + objKey;
        if (obj[objKey] && typeof obj[objKey] === 'object') {
            return walk(obj[objKey], newKey, response); // take nested object, not key
        }
        if (!response.includes(newKey)) { // do you expect duplicates?
            response.push(newKey);
        }
    });
    return response;
}
  

当我尝试运行此代码时,出现“ RangeError:超出了最大调用堆栈大小”

正确的是,您使用一个字符串(对象的键),并且对于每个字符,任何非空字符串都具有属性。并将此字符串移交给下一个具有相同结果的递归。

console.log(Object.keys("foo"));