example.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Designed to be run from Node.js - i.e. "node example.js"
  2. var XmlDocument = require('../lib/xmldoc').XmlDocument;
  3. // Demonstrate parsing an in-memory XML string
  4. var xmlString = '<suggestions><book title="Twilight"/><book title="Twister"/></suggestions>';
  5. var suggestions = new XmlDocument(xmlString);
  6. // Demonstrate how toString() will pretty-print the XML for debugging
  7. console.log("Parsed: \n%s", suggestions);
  8. // Demonstrate a simple eachChild() loop, printing our book titles
  9. suggestions.eachChild(function(book) {
  10. console.log("Found book with title: '%s'", book.attr.title);
  11. console.log("==> The <book> tag started at position %s and the complete element ended at line %s, column %s, position %s.", book.startTagPosition, book.line, book.column, book.position);
  12. });
  13. // Now load an XML file from disk and parse it
  14. var fs = require('fs'),
  15. path = require('path');
  16. fs.readFile(path.join(__dirname, "test.xml"), 'utf8', function (err,data) {
  17. if (err) {
  18. return console.log(err);
  19. }
  20. // Parse the XML
  21. var results = new XmlDocument(data);
  22. // Demonstrate toString() with an option to abbreviate long strings and compress the output
  23. console.log("Parsed: \n%s", results.toString({trimmed:true, compressed:true}));
  24. // Pull out the <books> node
  25. var books = results.childNamed("books");
  26. // Demonstrate firstChild/lastChild
  27. console.log("First book has ISBN '%s', last book has ISBN '%s'", books.firstChild.attr.isbn, books.lastChild.attr.isbn);
  28. // Print out the ISBNs
  29. books.eachChild(function (book) {
  30. console.log("Found book with ISBN '%s'", book.attr.isbn);
  31. });
  32. // Look for all children with a certain node name
  33. var allBooks = books.childrenNamed("book");
  34. // The result is an array of <book> XmlElement instances
  35. console.log("Found %s books.", allBooks.length);
  36. // Search for a particular book
  37. var twilight = books.childWithAttribute("isbn","478-2-23-765712-2");
  38. // Result is a single XmlElement instance for <book>
  39. console.log("Title of book with given ISBN: '%s'", twilight.valueWithPath("title"));
  40. return null;
  41. });