租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

507 lines
18 KiB

2 months ago
  1. node-xml2js
  2. ===========
  3. Ever had the urge to parse XML? And wanted to access the data in some sane,
  4. easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is
  5. what you're looking for!
  6. Description
  7. ===========
  8. Simple XML to JavaScript object converter. It supports bi-directional conversion.
  9. Uses [sax-js](https://github.com/isaacs/sax-js/) and
  10. [xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js/).
  11. Note: If you're looking for a full DOM parser, you probably want
  12. [JSDom](https://github.com/tmpvar/jsdom).
  13. Installation
  14. ============
  15. Simplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm
  16. install xml2js` which will download xml2js and all dependencies.
  17. xml2js is also available via [Bower](http://bower.io/), just `bower install
  18. xml2js` which will download xml2js and all dependencies.
  19. Usage
  20. =====
  21. No extensive tutorials required because you are a smart developer! The task of
  22. parsing XML should be an easy one, so let's make it so! Here's some examples.
  23. Shoot-and-forget usage
  24. ----------------------
  25. You want to parse XML as simple and easy as possible? It's dangerous to go
  26. alone, take this:
  27. ```javascript
  28. var parseString = require('xml2js').parseString;
  29. var xml = "<root>Hello xml2js!</root>"
  30. parseString(xml, function (err, result) {
  31. console.dir(result);
  32. });
  33. ```
  34. Can't get easier than this, right? This works starting with `xml2js` 0.2.3.
  35. With CoffeeScript it looks like this:
  36. ```coffeescript
  37. {parseString} = require 'xml2js'
  38. xml = "<root>Hello xml2js!</root>"
  39. parseString xml, (err, result) ->
  40. console.dir result
  41. ```
  42. If you need some special options, fear not, `xml2js` supports a number of
  43. options (see below), you can specify these as second argument:
  44. ```javascript
  45. parseString(xml, {trim: true}, function (err, result) {
  46. });
  47. ```
  48. Simple as pie usage
  49. -------------------
  50. That's right, if you have been using xml-simple or a home-grown
  51. wrapper, this was added in 0.1.11 just for you:
  52. ```javascript
  53. var fs = require('fs'),
  54. xml2js = require('xml2js');
  55. var parser = new xml2js.Parser();
  56. fs.readFile(__dirname + '/foo.xml', function(err, data) {
  57. parser.parseString(data, function (err, result) {
  58. console.dir(result);
  59. console.log('Done');
  60. });
  61. });
  62. ```
  63. Look ma, no event listeners!
  64. You can also use `xml2js` from
  65. [CoffeeScript](https://github.com/jashkenas/coffeescript), further reducing
  66. the clutter:
  67. ```coffeescript
  68. fs = require 'fs',
  69. xml2js = require 'xml2js'
  70. parser = new xml2js.Parser()
  71. fs.readFile __dirname + '/foo.xml', (err, data) ->
  72. parser.parseString data, (err, result) ->
  73. console.dir result
  74. console.log 'Done.'
  75. ```
  76. But what happens if you forget the `new` keyword to create a new `Parser`? In
  77. the middle of a nightly coding session, it might get lost, after all. Worry
  78. not, we got you covered! Starting with 0.2.8 you can also leave it out, in
  79. which case `xml2js` will helpfully add it for you, no bad surprises and
  80. inexplicable bugs!
  81. Promise usage
  82. -------------
  83. ```javascript
  84. var xml2js = require('xml2js');
  85. var xml = '<foo></foo>';
  86. // With parser
  87. var parser = new xml2js.Parser(/* options */);
  88. parser.parseStringPromise(xml).then(function (result) {
  89. console.dir(result);
  90. console.log('Done');
  91. })
  92. .catch(function (err) {
  93. // Failed
  94. });
  95. // Without parser
  96. xml2js.parseStringPromise(xml /*, options */).then(function (result) {
  97. console.dir(result);
  98. console.log('Done');
  99. })
  100. .catch(function (err) {
  101. // Failed
  102. });
  103. ```
  104. Parsing multiple files
  105. ----------------------
  106. If you want to parse multiple files, you have multiple possibilities:
  107. * You can create one `xml2js.Parser` per file. That's the recommended one
  108. and is promised to always *just work*.
  109. * You can call `reset()` on your parser object.
  110. * You can hope everything goes well anyway. This behaviour is not
  111. guaranteed work always, if ever. Use option #1 if possible. Thanks!
  112. So you wanna some JSON?
  113. -----------------------
  114. Just wrap the `result` object in a call to `JSON.stringify` like this
  115. `JSON.stringify(result)`. You get a string containing the JSON representation
  116. of the parsed object that you can feed to JSON-hungry consumers.
  117. Displaying results
  118. ------------------
  119. You might wonder why, using `console.dir` or `console.log` the output at some
  120. level is only `[Object]`. Don't worry, this is not because `xml2js` got lazy.
  121. That's because Node uses `util.inspect` to convert the object into strings and
  122. that function stops after `depth=2` which is a bit low for most XML.
  123. To display the whole deal, you can use `console.log(util.inspect(result, false,
  124. null))`, which displays the whole result.
  125. So much for that, but what if you use
  126. [eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it
  127. truncates the output with `…`? Don't fear, there's also a solution for that,
  128. you just need to increase the `maxLength` limit by creating a custom inspector
  129. `var inspect = require('eyes').inspector({maxLength: false})` and then you can
  130. easily `inspect(result)`.
  131. XML builder usage
  132. -----------------
  133. Since 0.4.0, objects can be also be used to build XML:
  134. ```javascript
  135. var xml2js = require('xml2js');
  136. var obj = {name: "Super", Surname: "Man", age: 23};
  137. var builder = new xml2js.Builder();
  138. var xml = builder.buildObject(obj);
  139. ```
  140. will result in:
  141. ```xml
  142. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  143. <root>
  144. <name>Super</name>
  145. <Surname>Man</Surname>
  146. <age>23</age>
  147. </root>
  148. ```
  149. At the moment, a one to one bi-directional conversion is guaranteed only for
  150. default configuration, except for `attrkey`, `charkey` and `explicitArray` options
  151. you can redefine to your taste. Writing CDATA is supported via setting the `cdata`
  152. option to `true`.
  153. To specify attributes:
  154. ```javascript
  155. var xml2js = require('xml2js');
  156. var obj = {root: {$: {id: "my id"}, _: "my inner text"}};
  157. var builder = new xml2js.Builder();
  158. var xml = builder.buildObject(obj);
  159. ```
  160. will result in:
  161. ```xml
  162. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  163. <root id="my id">my inner text</root>
  164. ```
  165. ### Adding xmlns attributes
  166. You can generate XML that declares XML namespace prefix / URI pairs with xmlns attributes.
  167. Example declaring a default namespace on the root element:
  168. ```javascript
  169. let obj = {
  170. Foo: {
  171. $: {
  172. "xmlns": "http://foo.com"
  173. }
  174. }
  175. };
  176. ```
  177. Result of `buildObject(obj)`:
  178. ```xml
  179. <Foo xmlns="http://foo.com"/>
  180. ```
  181. Example declaring non-default namespaces on non-root elements:
  182. ```javascript
  183. let obj = {
  184. 'foo:Foo': {
  185. $: {
  186. 'xmlns:foo': 'http://foo.com'
  187. },
  188. 'bar:Bar': {
  189. $: {
  190. 'xmlns:bar': 'http://bar.com'
  191. }
  192. }
  193. }
  194. }
  195. ```
  196. Result of `buildObject(obj)`:
  197. ```xml
  198. <foo:Foo xmlns:foo="http://foo.com">
  199. <bar:Bar xmlns:bar="http://bar.com"/>
  200. </foo:Foo>
  201. ```
  202. Processing attribute, tag names and values
  203. ------------------------------------------
  204. Since 0.4.1 you can optionally provide the parser with attribute name and tag name processors as well as element value processors (Since 0.4.14, you can also optionally provide the parser with attribute value processors):
  205. ```javascript
  206. function nameToUpperCase(name){
  207. return name.toUpperCase();
  208. }
  209. //transform all attribute and tag names and values to uppercase
  210. parseString(xml, {
  211. tagNameProcessors: [nameToUpperCase],
  212. attrNameProcessors: [nameToUpperCase],
  213. valueProcessors: [nameToUpperCase],
  214. attrValueProcessors: [nameToUpperCase]},
  215. function (err, result) {
  216. // processed data
  217. });
  218. ```
  219. The `tagNameProcessors` and `attrNameProcessors` options
  220. accept an `Array` of functions with the following signature:
  221. ```javascript
  222. function (name){
  223. //do something with `name`
  224. return name
  225. }
  226. ```
  227. The `attrValueProcessors` and `valueProcessors` options
  228. accept an `Array` of functions with the following signature:
  229. ```javascript
  230. function (value, name) {
  231. //`name` will be the node name or attribute name
  232. //do something with `value`, (optionally) dependent on the node/attr name
  233. return value
  234. }
  235. ```
  236. Some processors are provided out-of-the-box and can be found in `lib/processors.js`:
  237. - `normalize`: transforms the name to lowercase.
  238. (Automatically used when `options.normalize` is set to `true`)
  239. - `firstCharLowerCase`: transforms the first character to lower case.
  240. E.g. 'MyTagName' becomes 'myTagName'
  241. - `stripPrefix`: strips the xml namespace prefix. E.g `<foo:Bar/>` will become 'Bar'.
  242. (N.B.: the `xmlns` prefix is NOT stripped.)
  243. - `parseNumbers`: parses integer-like strings as integers and float-like strings as floats
  244. E.g. "0" becomes 0 and "15.56" becomes 15.56
  245. - `parseBooleans`: parses boolean-like strings to booleans
  246. E.g. "true" becomes true and "False" becomes false
  247. Options
  248. =======
  249. Apart from the default settings, there are a number of options that can be
  250. specified for the parser. Options are specified by ``new Parser({optionName:
  251. value})``. Possible options are:
  252. * `attrkey` (default: `$`): Prefix that is used to access the attributes.
  253. Version 0.1 default was `@`.
  254. * `charkey` (default: `_`): Prefix that is used to access the character
  255. content. Version 0.1 default was `#`.
  256. * `explicitCharkey` (default: `false`) Determines whether or not to use
  257. a `charkey` prefix for elements with no attributes.
  258. * `trim` (default: `false`): Trim the whitespace at the beginning and end of
  259. text nodes.
  260. * `normalizeTags` (default: `false`): Normalize all tag names to lowercase.
  261. * `normalize` (default: `false`): Trim whitespaces inside text nodes.
  262. * `explicitRoot` (default: `true`): Set this if you want to get the root
  263. node in the resulting object.
  264. * `emptyTag` (default: `''`): what will the value of empty nodes be. In case
  265. you want to use an empty object as a default value, it is better to provide a factory
  266. function `() => ({})` instead. Without this function a plain object would
  267. become a shared reference across all occurrences with unwanted behavior.
  268. * `explicitArray` (default: `true`): Always put child nodes in an array if
  269. true; otherwise an array is created only if there is more than one.
  270. * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create
  271. text nodes.
  272. * `mergeAttrs` (default: `false`): Merge attributes and child elements as
  273. properties of the parent, instead of keying attributes off a child
  274. attribute object. This option is ignored if `ignoreAttrs` is `true`.
  275. * `validator` (default `null`): You can specify a callable that validates
  276. the resulting structure somehow, however you want. See unit tests
  277. for an example.
  278. * `xmlns` (default `false`): Give each element a field usually called '$ns'
  279. (the first character is the same as attrkey) that contains its local name
  280. and namespace URI.
  281. * `explicitChildren` (default `false`): Put child elements to separate
  282. property. Doesn't work with `mergeAttrs = true`. If element has no children
  283. then "children" won't be created. Added in 0.2.5.
  284. * `childkey` (default `$$`): Prefix that is used to access child elements if
  285. `explicitChildren` is set to `true`. Added in 0.2.5.
  286. * `preserveChildrenOrder` (default `false`): Modifies the behavior of
  287. `explicitChildren` so that the value of the "children" property becomes an
  288. ordered array. When this is `true`, every node will also get a `#name` field
  289. whose value will correspond to the XML nodeName, so that you may iterate
  290. the "children" array and still be able to determine node names. The named
  291. (and potentially unordered) properties are also retained in this
  292. configuration at the same level as the ordered "children" array. Added in
  293. 0.4.9.
  294. * `charsAsChildren` (default `false`): Determines whether chars should be
  295. considered children if `explicitChildren` is on. Added in 0.2.5.
  296. * `includeWhiteChars` (default `false`): Determines whether whitespace-only
  297. text nodes should be included. Added in 0.4.17.
  298. * `async` (default `false`): Should the callbacks be async? This *might* be
  299. an incompatible change if your code depends on sync execution of callbacks.
  300. Future versions of `xml2js` might change this default, so the recommendation
  301. is to not depend on sync execution anyway. Added in 0.2.6.
  302. * `strict` (default `true`): Set sax-js to strict or non-strict parsing mode.
  303. Defaults to `true` which is *highly* recommended, since parsing HTML which
  304. is not well-formed XML might yield just about anything. Added in 0.2.7.
  305. * `attrNameProcessors` (default: `null`): Allows the addition of attribute
  306. name processing functions. Accepts an `Array` of functions with following
  307. signature:
  308. ```javascript
  309. function (name){
  310. //do something with `name`
  311. return name
  312. }
  313. ```
  314. Added in 0.4.14
  315. * `attrValueProcessors` (default: `null`): Allows the addition of attribute
  316. value processing functions. Accepts an `Array` of functions with following
  317. signature:
  318. ```javascript
  319. function (value, name){
  320. //do something with `name`
  321. return name
  322. }
  323. ```
  324. Added in 0.4.1
  325. * `tagNameProcessors` (default: `null`): Allows the addition of tag name
  326. processing functions. Accepts an `Array` of functions with following
  327. signature:
  328. ```javascript
  329. function (name){
  330. //do something with `name`
  331. return name
  332. }
  333. ```
  334. Added in 0.4.1
  335. * `valueProcessors` (default: `null`): Allows the addition of element value
  336. processing functions. Accepts an `Array` of functions with following
  337. signature:
  338. ```javascript
  339. function (value, name){
  340. //do something with `name`
  341. return name
  342. }
  343. ```
  344. Added in 0.4.6
  345. Options for the `Builder` class
  346. -------------------------------
  347. These options are specified by ``new Builder({optionName: value})``.
  348. Possible options are:
  349. * `attrkey` (default: `$`): Prefix that is used to access the attributes.
  350. Version 0.1 default was `@`.
  351. * `charkey` (default: `_`): Prefix that is used to access the character
  352. content. Version 0.1 default was `#`.
  353. * `rootName` (default `root` or the root key name): root element name to be used in case
  354. `explicitRoot` is `false` or to override the root element name.
  355. * `renderOpts` (default `{ 'pretty': true, 'indent': ' ', 'newline': '\n' }`):
  356. Rendering options for xmlbuilder-js.
  357. * pretty: prettify generated XML
  358. * indent: whitespace for indentation (only when pretty)
  359. * newline: newline char (only when pretty)
  360. * `xmldec` (default `{ 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }`:
  361. XML declaration attributes.
  362. * `xmldec.version` A version number string, e.g. 1.0
  363. * `xmldec.encoding` Encoding declaration, e.g. UTF-8
  364. * `xmldec.standalone` standalone document declaration: true or false
  365. * `doctype` (default `null`): optional DTD. Eg. `{'ext': 'hello.dtd'}`
  366. * `headless` (default: `false`): omit the XML header. Added in 0.4.3.
  367. * `allowSurrogateChars` (default: `false`): allows using characters from the Unicode
  368. surrogate blocks.
  369. * `cdata` (default: `false`): wrap text nodes in `<![CDATA[ ... ]]>` instead of
  370. escaping when necessary. Does not add `<![CDATA[ ... ]]>` if it is not required.
  371. Added in 0.4.5.
  372. `renderOpts`, `xmldec`,`doctype` and `headless` pass through to
  373. [xmlbuilder-js](https://github.com/oozcitak/xmlbuilder-js).
  374. Updating to new version
  375. =======================
  376. Version 0.2 changed the default parsing settings, but version 0.1.14 introduced
  377. the default settings for version 0.2, so these settings can be tried before the
  378. migration.
  379. ```javascript
  380. var xml2js = require('xml2js');
  381. var parser = new xml2js.Parser(xml2js.defaults["0.2"]);
  382. ```
  383. To get the 0.1 defaults in version 0.2 you can just use
  384. `xml2js.defaults["0.1"]` in the same place. This provides you with enough time
  385. to migrate to the saner way of parsing in `xml2js` 0.2. We try to make the
  386. migration as simple and gentle as possible, but some breakage cannot be
  387. avoided.
  388. So, what exactly did change and why? In 0.2 we changed some defaults to parse
  389. the XML in a more universal and sane way. So we disabled `normalize` and `trim`
  390. so `xml2js` does not cut out any text content. You can reenable this at will of
  391. course. A more important change is that we return the root tag in the resulting
  392. JavaScript structure via the `explicitRoot` setting, so you need to access the
  393. first element. This is useful for anybody who wants to know what the root node
  394. is and preserves more information. The last major change was to enable
  395. `explicitArray`, so everytime it is possible that one might embed more than one
  396. sub-tag into a tag, xml2js >= 0.2 returns an array even if the array just
  397. includes one element. This is useful when dealing with APIs that return
  398. variable amounts of subtags.
  399. Running tests, development
  400. ==========================
  401. [![Build Status](https://travis-ci.org/Leonidas-from-XIV/node-xml2js.svg?branch=master)](https://travis-ci.org/Leonidas-from-XIV/node-xml2js)
  402. [![Coverage Status](https://coveralls.io/repos/Leonidas-from-XIV/node-xml2js/badge.svg?branch=)](https://coveralls.io/r/Leonidas-from-XIV/node-xml2js?branch=master)
  403. [![Dependency Status](https://david-dm.org/Leonidas-from-XIV/node-xml2js.svg)](https://david-dm.org/Leonidas-from-XIV/node-xml2js)
  404. The development requirements are handled by npm, you just need to install them.
  405. We also have a number of unit tests, they can be run using `npm test` directly
  406. from the project root. This runs zap to discover all the tests and execute
  407. them.
  408. If you like to contribute, keep in mind that `xml2js` is written in
  409. CoffeeScript, so don't develop on the JavaScript files that are checked into
  410. the repository for convenience reasons. Also, please write some unit test to
  411. check your behaviour and if it is some user-facing thing, add some
  412. documentation to this README, so people will know it exists. Thanks in advance!
  413. Getting support
  414. ===============
  415. Please, if you have a problem with the library, first make sure you read this
  416. README. If you read this far, thanks, you're good. Then, please make sure your
  417. problem really is with `xml2js`. It is? Okay, then I'll look at it. Send me a
  418. mail and we can talk. Please don't open issues, as I don't think that is the
  419. proper forum for support problems. Some problems might as well really be bugs
  420. in `xml2js`, if so I'll let you know to open an issue instead :)
  421. But if you know you really found a bug, feel free to open an issue instead.