XML Parser that works for both browser and Node.js?

雨燕双飞 提交于 2019-12-14 01:36:47

问题


Problem at hand: I have XML on the client side and the server side, but there's no consistent way to parse XML on both sides.

Most browsers have DOMParser. But Node.js doesn't have a built-in XML parser. There are lots of modules for Node.js for XML parsing, but I'm looking for a XML parser API that is consistent for both front-end and back-end. In other words, I'm looking for a XML parsing module that can be used in Node.js like this

const parser = require(magic_library);
const doc = parser.parseFromString(xml_string, 'application/xml');

and also in the browser like this

<script src="magic_library"></script>
<script>
  const doc = parser.parseFromString(xml_string, 'application/xml');
</script>

回答1:


Try fast-xml-parser

In Node.js

var fastXmlParser = require('fast-xml-parser');
var jsonObj = fastXmlParser.parse(xmlData);

// when a tag has attributes 
var options = {
    attrPrefix : "@_",
    textNodeName : "#text",
    ignoreNonTextNodeAttr : true,
    ignoreTextNodeAttr : true,
    ignoreNameSpace : true,
    ignoreRootElement : false,
    textNodeConversion : true,
    textAttrConversion : false,
    arrayMode : false
};
if(fastXmlParser.validate(xmlData)=== true){//optional 
    var jsonObj = fastXmlParser.parse(xmlData,options);
}

//Intermediate obj 
var tObj = fastXmlParser.getTraversalObj(xmlData,options);
var jsonObj = fastXmlParser.convertToJson(tObj);

And in browser

var isValid = parser.validate(xmlData);
var jsonObj = parser.parse(xmlData);


来源:https://stackoverflow.com/questions/45685100/xml-parser-that-works-for-both-browser-and-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!