Example - lemmabit/xml-pulley GitHub Wiki

A simple example

This example parses a ridiculously impractical XML format that encodes a string using a dictionary.

XML

<root>
  <dict>
    <entry name="ha1">Ha</entry>
    <entry name="ha2"> ha</entry>
  </dict>
  <dict>
    <entry name="stop">.</entry>
  </dict>
  <item>ha1 </item>
  <item>ha2 </item>
  <item>ha2 </item>
  <item>stop</item>
</root>

JavaScript

var xmlPulley = require('xml-pulley');
var makePulley = xmlPulley.makePulley;


var dict = {}; // map of dictionary keys to items
var out = '';  // stores the resulting string


function parseRoot(pulley) {
  // consume <root>
  pulley.expectName('root');
  
  // loop over the contents until a closing tag is encountered
  pulley.loop(function(pulley) {
    if(pulley.check('opentag').name !== 'dict') {
      // all of the <dict>s have been parsed
      // return true to break out of the loop and move on to <item>s
      return true;
    }
    parseDict(pulley);
  });
  
  // do it again with a different loop
  pulley.loop(function(pulley) {
    parseItem(pulley);
  });
  
   // consume </root>
  pulley.expectName('root', 'closetag');
}


function parseDict(pulley) {
  pulley.loopTag(parseEntry, 'dict'); // loop over the contents of the <dict>
}
function parseEntry(pulley) {
  var tag = pulley.expectName('entry'); // consume <entry>
  var name = tag.attributes.name; // <entry name="...">
  var contents = pulley.nextText().rawText; // get untrimmed text
  dict[name] = contents; // add entry to the dictionary
  pulley.expectName('entry', 'closetag'); // consume </entry>
}
function parseItem(pulley) {
  pulley.expectName('item'); // consume <item>
  var name = pulley.nextText().text; // get trimmed text
  out += dict[name]; // look up name in the dictionary and append entry
  pulley.expectName('item', 'closetag'); // consume </item>
}


var pulley = makePulley(xmlString, {
  skipWhitespaceOnly: true, // skip text nodes that are only whitespace
  trim: true // trim whitespace from the start and end of text nodes
});

parseRoot(pulley);

console.log(out);

Output

Ha ha ha.
⚠️ **GitHub.com Fallback** ⚠️