home *** CD-ROM | disk | FTP | other *** search
/ PC go! 2014 January / PCgo_CD_14_01.iso / node_modules / xml2js / README.md < prev   
Encoding:
Text File  |  2013-04-09  |  8.9 KB  |  240 lines

  1. node-xml2js
  2. ===========
  3.  
  4. Ever had the urge to parse XML? And wanted to access the data in some sane,
  5. easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is
  6. what you're looking for!
  7.  
  8. Description
  9. ===========
  10.  
  11. Simple XML to JavaScript object converter. Uses
  12. [sax-js](https://github.com/isaacs/sax-js/).
  13.  
  14. Note: If you're looking for a full DOM parser, you probably want
  15. [JSDom](https://github.com/tmpvar/jsdom).
  16.  
  17. Installation
  18. ============
  19.  
  20. Simplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm
  21. install xml2js` which will download xml2js and all dependencies.
  22.  
  23. Usage
  24. =====
  25.  
  26. No extensive tutorials required because you are a smart developer! The task of
  27. parsing XML should be an easy one, so let's make it so! Here's some examples.
  28.  
  29. Shoot-and-forget usage
  30. ----------------------
  31.  
  32. You want to parse XML as simple and easy as possible? It's dangerous to go
  33. alone, take this:
  34.  
  35. ```javascript
  36. var parseString = require('xml2js').parseString;
  37. var xml = "<root>Hello xml2js!</root>"
  38. parseString(xml, function (err, result) {
  39.     console.dir(result);
  40. });
  41. ```
  42.  
  43. Can't get easier than this, right? This works starting with `xml2js` 0.2.3.
  44. With CoffeeScript it looks like this:
  45.  
  46. ```coffeescript
  47. parseString = require('xml2js').parseString
  48. xml = "<root>Hello xml2js!</root>"
  49. parseString xml, (err, result) ->
  50.     console.dir result
  51. ```
  52.  
  53. If you need some special options, fear not, `xml2js` supports a number of
  54. options (see below), you can specify these as second argument:
  55.  
  56. ```javascript
  57. parseString(xml, {trim: true}, function (err, result) {
  58. });
  59. ```
  60.  
  61. Simple as pie usage
  62. -------------------
  63.  
  64. That's right, if you have been using xml-simple or a home-grown
  65. wrapper, this is was added in 0.1.11 just for you:
  66.  
  67. ```javascript
  68. var fs = require('fs'),
  69.     xml2js = require('xml2js');
  70.  
  71. var parser = new xml2js.Parser();
  72. fs.readFile(__dirname + '/foo.xml', function(err, data) {
  73.     parser.parseString(data, function (err, result) {
  74.         console.dir(result);
  75.         console.log('Done');
  76.     });
  77. });
  78. ```
  79.  
  80. Look ma, no event listeners!
  81.  
  82. You can also use `xml2js` from
  83. [CoffeeScript](http://jashkenas.github.com/coffee-script/), further reducing
  84. the clutter:
  85.  
  86. ```coffeescript
  87. fs = require 'fs',
  88. xml2js = require 'xml2js'
  89.  
  90. parser = new xml2js.Parser()
  91. fs.readFile __dirname + '/foo.xml', (err, data) ->
  92.   parser.parseString data, (err, result) ->
  93.     console.dir result
  94.     console.log 'Done.'
  95. ```
  96.  
  97. "Traditional" usage
  98. -------------------
  99.  
  100. Alternatively you can still use the traditional `addListener` variant that was
  101. supported since forever:
  102.  
  103. ```javascript
  104. var fs = require('fs'),
  105.     xml2js = require('xml2js');
  106.  
  107. var parser = new xml2js.Parser();
  108. parser.addListener('end', function(result) {
  109.     console.dir(result);
  110.     console.log('Done.');
  111. });
  112. fs.readFile(__dirname + '/foo.xml', function(err, data) {
  113.     parser.parseString(data);
  114. });
  115. ```
  116.  
  117. If you want to parse multiple files, you have multiple possibilites:
  118.  
  119.   * You can create one `xml2js.Parser` per file. That's the recommended one
  120.     and is promised to always *just work*.
  121.   * You can call `reset()` on your parser object.
  122.   * You can hope everything goes well anyway. This behaviour is not
  123.     guaranteed work always, if ever. Use option #1 if possible. Thanks!
  124.  
  125. So you wanna some JSON?
  126. -----------------------
  127.  
  128. Just wrap the `result` object in a call to `JSON.stringify` like this
  129. `JSON.stringify(result)`. You get a string containing the JSON representation
  130. of the parsed object that you can feed to JSON-hungry consumers.
  131.  
  132. Displaying results
  133. ------------------
  134.  
  135. You might wonder why, using `console.dir` or `console.log` the output at some
  136. level is only `[Object]`. Don't worry, this is not because xml2js got lazy.
  137. That's because Node uses `util.inspect` to convert the object into strings and
  138. that function stops after `depth=2` which is a bit low for most XML.
  139.  
  140. To display the whole deal, you can use `console.log(util.inspect(result, false,
  141. null))`, which displays the whole result.
  142.  
  143. So much for that, but what if you use
  144. [eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it
  145. truncates the output with `ΓǪ`? Don't fear, there's also a solution for that,
  146. you just need to increase the `maxLength` limit by creating a custom inspector
  147. `var inspect = require('eyes').inspector({maxLength: false})` and then you can
  148. easily `inspect(result)`.
  149.  
  150. Options
  151. =======
  152.  
  153. Apart from the default settings, there is a number of options that can be
  154. specified for the parser. Options are specified by ``new Parser({optionName:
  155. value})``. Possible options are:
  156.  
  157.   * `attrkey` (default: `$`): Prefix that is used to access the attributes.
  158.     Version 0.1 default was `@`.
  159.   * `charkey` (default: `_`): Prefix that is used to access the character
  160.     content. Version 0.1 default was `#`.
  161.   * `explicitCharkey` (default: `false`)
  162.   * `trim` (default: `false`): Trim the whitespace at the beginning and end of
  163.     text nodes.
  164.   * `normalizeTags` (default: `false`): Normalize all tag names to lowercase.
  165.   * `normalize` (default: `false`): Trim whitespaces inside text nodes.
  166.   * `explicitRoot` (default: `true`): Set this if you want to get the root
  167.     node in the resulting object.
  168.   * `emptyTag` (default: `undefined`): what will the value of empty nodes be.
  169.     Default is `{}`.
  170.   * `explicitArray` (default: `true`): Always put child nodes in an array if
  171.     true; otherwise an array is created only if there is more than one.
  172.   * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create
  173.     text nodes.
  174.   * `mergeAttrs` (default: `false`): Merge attributes and child elements as
  175.     properties of the parent, instead of keying attributes off a child
  176.     attribute object. This option is ignored if `ignoreAttrs` is `false`.
  177.   * `validator` (default `null`): You can specify a callable that validates
  178.     the resulting structure somehow, however you want. See unit tests
  179.     for an example.
  180.   * `xmlns` (default `false`): Give each element a field usually called '$ns'
  181.     (the first character is the same as attrkey) that contains its local name
  182.     and namespace URI.
  183.   * `explicitChildren` (default `false`): Put child elements to separate
  184.     property. Doesn't work with `mergeAttrs = true`. If element has no children
  185.     then "children" won't be created. Added in 0.2.5.
  186.   * `childkey` (default `$$`): Prefix that is used to access child elements if
  187.     `explicitChildren` is set to `true`. Added in 0.2.5.
  188.   * `charsAsChildren` (default `false`): Determines whether chars should be
  189.     considered children if `explicitChildren` is on. Added in 0.2.5.
  190.   * `async` (default `false`): Should the callbacks be async? This *might* be
  191.     an incompatible change if your code depends on sync execution of callbacks.
  192.     xml2js 0.3 might change this default, so the recommendation is to not
  193.     depend on sync execution anyway. Added in 0.2.6.
  194.  
  195. Updating to new version
  196. =======================
  197.  
  198. Version 0.2 changed the default parsing settings, but version 0.1.14 introduced
  199. the default settings for version 0.2, so these settings can be tried before the
  200. migration.
  201.  
  202. ```javascript
  203. var xml2js = require('xml2js');
  204. var parser = new xml2js.Parser(xml2js.defaults["0.2"]);
  205. ```
  206.  
  207. To get the 0.1 defaults in version 0.2 you can just use
  208. `xml2js.defaults["0.1"]` in the same place. This provides you with enough time
  209. to migrate to the saner way of parsing in xml2js 0.2. We try to make the
  210. migration as simple and gentle as possible, but some breakage cannot be
  211. avoided.
  212.  
  213. So, what exactly did change and why? In 0.2 we changed some defaults to parse
  214. the XML in a more universal and sane way. So we disabled `normalize` and `trim`
  215. so xml2js does not cut out any text content. You can reenable this at will of
  216. course. A more important change is that we return the root tag in the resulting
  217. JavaScript structure via the `explicitRoot` setting, so you need to access the
  218. first element. This is useful for anybody who wants to know what the root node
  219. is and preserves more information. The last major change was to enable
  220. `explicitArray`, so everytime it is possible that one might embed more than one
  221. sub-tag into a tag, xml2js >= 0.2 returns an array even if the array just
  222. includes one element. This is useful when dealing with APIs that return
  223. variable amounts of subtags.
  224.  
  225. Running tests, development
  226. ==========================
  227.  
  228. [![Build Status](https://secure.travis-ci.org/Leonidas-from-XIV/node-xml2js.png?branch=master)](https://travis-ci.org/Leonidas-from-XIV/node-xml2js)
  229.  
  230. The development requirements are handled by npm, you just need to install them.
  231. We also have a number of unit tests, they can be run using `npm test` directly
  232. from the project root. This runs zap to discover all the tests and execute
  233. them.
  234.  
  235. If you like to contribute, keep in mind that xml2js is written in CoffeeScript,
  236. so don't develop on the JavaScript files that are checked into the repository
  237. for convenience reasons. Also, please write some unit test to check your
  238. behaviour and if it is some user-facing thing, add some documentation to this
  239. README, so people will know it exists. Thanks in advance!
  240.