Requirement: Processing an XML file in node CDATA processing a particular field
Environment: Window + node +webstorm
Module: XML2JS
Code:
varXml2js = require (' Xml2js '));varFS = require (' FS '); varParser =NewXml2js. Parser ({explicitarray:false,//do not use array modeIgnoreattrs:false,//do not ignore propertiesStrcdkey: "Headline,keyword,datacontent"//a special key value that you define yourself }); varCbuilder =NewXml2js. Builder ({CDATA:true }); Fs.readfile (‘.. /public/test.xml ',function(err, data) {//Data Type ==>buffer if(Err) { //callback (ERR)return} parser.parsestring (data,function(err, result) {if(err) {//callback (ERR);//Exception callback return; } //starts processing the XML object result----and JSON format dot. Call on the line //such as:Result. Items.Item.FirstCreateTime =NewDate (); //Use the above method if the XML document items are under one item
//If there is more than one item under the XML document items, use the following methodResult. Items.item[0]. Firstcreatetime =NewDate (); //as in an XML document, one would like to append to multiple processing as follows:Result. items= {"Item": [Result. Items.item]}; Result. Items.push ({The JSON format of the internal structure of the item}); //This step allows you to convert the JSON format file to XML formatresult =cbuilder.buildobject (Result); Fs.writefile ("./public/newdemo.xml", result,function(err) {if(ERR) {//callback (ERR); return} callback ("OK") }); }); })
But we can do it in one step.
Yes, that's what you define, Strcdkey .
Find the Xml2js module under Lib xml2js.js file modification 2 places
A. Theoretically, this place can be a no-no-no, but the test didn't produce any effect .
Exports.defaults = {
Strcdkey: ""
}
B. Place the Builder.prototype.buildObject method under the
if (typeof child = = = ' String ' && _this.options.cdata && requirescdata (Child))) {
Switch
if (typeof child = = = ' String ' && ((_this.options.cdata && requirescdata (child)) | | _ This.options.strCdkey.indexOf (Key) >-1)) {
Done!!!
Development time 20180123 Note version, etc.
Node JS XML CDATA