Example analysis of pits encountered in the process of analyzing xml by nodejs module xml2js

  • 2021-08-05 08:17:57
  • OfStack

In this paper, an example is given to describe the pits encountered by nodejs module xml2js in the process of parsing xml. Share it for your reference, as follows:

In one project, the nodejs module xml2js is used to parse the data of xml and xml as follows:


<xml>
<MsgId>6197906553041859764</MsgId>
</xml>

Using xml2js. parseString method in xml2js, it was originally thought to be an json, but it always failed to analyze. The analysis result log is as follows:


{ xml: { MsgId: [ '6197906553041859764' ] } }

In the original xml, < MsgId > The package is a string, and the result is an array.

Later, I checked the official website of xml2js and found the following parameters:

explicitArray (default: true): Always put child nodes in an array if true; otherwise an array is created only if there is more than one.

Originally, xml2js will change the value of child nodes into an array by default. This pit is really big! ! ! It took half a day to check this problem.

Knowing the reason, the solution is also very simple. When calling xml2js. parseString, add the following parameters to explicitArray:


xml2js.parseString(buf, {explicitArray : false}, function(err, json) {
});

After modification, the following results are analyzed as follows:


{ xml: { MsgId: '6197906553041859764' } }

Now it becomes a string.

PS: Here are several online tools for xml operation for your reference:

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

Online Formatting XML/Online Compressing XML:
http://tools.ofstack.com/code/xmlformat

XML Online Compression/Formatting Tools:
http://tools.ofstack.com/code/xml_format_compress

XML code online formatting beautification tool:
http://tools.ofstack.com/code/xmlcodeformat

I hope this article is helpful to everyone's nodejs programming.


Related articles: