test.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var xmlreader = require('./xmlreader');
  2. var someXml = '<response id="1" shop="aldi">'
  3. + 'This is some other content'
  4. + '<who name="james">James May</who>'
  5. + '<who name="sam">'
  6. + 'Sam Decrock'
  7. + '<location>Belgium</location>'
  8. + '</who>'
  9. + '<who name="jack">Jack Johnsen</who>'
  10. + '<games age="6">'
  11. + '<game>Some great game</game>'
  12. + '<game>Some other great game</game>'
  13. + '</games>'
  14. + '<title>'
  15. + '<![CDATA[Some text between CDATA tags]]>'
  16. + '</title>'
  17. + '<note>These are some notes</note>'
  18. + '</response>'
  19. xmlreader.read(someXml, function (err, res){
  20. if(err) return console.log(err);
  21. // use .text() to get the content of a node:
  22. console.log( res.response.text() );
  23. // use .attributes() to get the attributes of a node:
  24. console.log( res.response.attributes().shop );
  25. console.log("");
  26. // using the .count() and the .at() function, you can loop through nodes with the same name:
  27. for(var i = 0; i < res.response.who.count(); i++){
  28. console.log( res.response.who.at(i).text() );
  29. }
  30. console.log("");
  31. // you can also use .each() to loop through the nodes of the same name:
  32. res.response.who.each(function (i, who){
  33. console.log( who.text() );
  34. });
  35. console.log("");
  36. console.log( res.response.who.at(1).text() ) ;
  37. console.log( res.response.who.at(1).location.text() );
  38. // you can also use .at() to get to nodes where there's only one of them:
  39. console.log( res.response.note.at(0).text() );
  40. console.log("");
  41. // or loop through them as if they were a series of nodes with the same name:
  42. res.response.note.each(function (i, note){
  43. console.log( note.text() );
  44. });
  45. console.log("");
  46. console.log( res.response.title.text() );
  47. console.log("");
  48. // you can also get the parent of a node using .parent():
  49. console.log( res.response.who.at(1).parent().attributes().id ) ;
  50. });