问题
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