Home >Web Front-end >JS Tutorial >nodejs parses xml string into instance of object
This article mainly introduces the method of nodejs to parse xml strings into objects, and involves the operation skills related to the parsing and conversion of xml format strings by nodejs. Friends who need it can refer to it. I hope it can help everyone.
var xmlreader = require("xmlreader"); var fs = require("fs"); var xml_string = '<response id="1" shop="aldi">' + 'This is some other content' + '<who name="james">James May</who>' + '<who name="sam">' + 'Sam Decrock' + '<location>Belgium</location>' + '</who>' + '<who name="jack">Jack Johnsen</who>' + '<games age="6">' + '<game>Some great game</game>' + '<game>Some other great game</game>' + '</games>' + '<note>These are some notes</note>' + '</response>'; xmlreader.read(xml_string, function(errors, response){ if(null !== errors ){ console.log(errors) return; } console.log( response.response ); console.log( response.response.text() ); });
Nothing new, let’s take a look at the output
The output result of the first sentence is:
##
{ attributes : [Function], parent : [Function], count : [Function], at : [Function], each : [Function], text : [Function], who : { array : [[Object], [Object], [Object]], count : [Function], at : [Function], each : [Function] }, games : { attributes : [Function], parent : [Function], count : [Function], at : [Function], each : [Function], game : { array : [Object], count : [Function], at : [Function], each : [Function] } }, note : { attributes : [Function], parent : [Function], count : [Function], at : [Function], each : [Function], text : [Function] } }The second sentence output:
This is some other contentBased on the output, we can guess what this thing is about. 1.
xmlreaderConvert xml to JSON object (this expression is not accurate, but everyone knows what it is).
2. The nested structure of the converted JSON object is the same as the nested structure of the original xml tag.
3. Depending on the number of times a certain tag appears at the same level in xml (once and multiple times), different corresponding objects will be generated. The above node is once and who is three times.
4. Provide some functions for operating attributes or traversing, etc.
attributes: Get all attributes. 2,
parent: Get the parent node. 3,
count: Get the number. 4,
at: Get the node whose subscript is the specified value. 5,
each: Traversal, the parameter is a function. 6,
text: Get the text within the node, only the text of the current node, excluding the text of the child nodes.
How to implement php to parse xml and generate sql statements
PHP parsing xml format data tool class Example sharing
The above is the detailed content of nodejs parses xml string into instance of object. For more information, please follow other related articles on the PHP Chinese website!