Nodejs implements a method example for parsing an xml string as an object, nodejsxml
This example describes how to parse xml strings as objects in nodejs. We will share this with you for your reference. The details are as follows:
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 novel. 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] }}
Output of the second sentence:
This is some other content
Based on the output, we can guess what happened.
1,xmlreader
Convert xml to a JSON object (this statement is not accurate, but you know what it is ).
2. The nested structure of the converted JSON object is the same as that of the original xml tag.
3. Different corresponding objects are generated according to the number of tags at the same level in xml (one time and multiple times). The preceding node is one time, and the who is three times.
4. provides functions for Operation attributes or traversal.
Meaning of each method:
1. attributes: Get all attributes.
2. parent: Get the parent node.
3. count: Obtain the number.
4. at: Get the node with the specified subscript.
5. each: traversal. The parameter is a function.
6. text: Get the text in the node. Only the text of the current node does not contain the text of the subnode.
PS: Here are some online tools for xml operations for your reference:
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat
XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress
XMLCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat
I hope this article will help you design nodejs programs.