xml-node.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var escapeAttribute = require('./escape-attribute').escapeAttribute;
  2. /**
  3. * Represents an XML node.
  4. * @api private
  5. */
  6. function XmlNode(name, children) {
  7. if (children === void 0) { children = []; }
  8. this.name = name;
  9. this.children = children;
  10. this.attributes = {};
  11. }
  12. XmlNode.prototype.addAttribute = function (name, value) {
  13. this.attributes[name] = value;
  14. return this;
  15. };
  16. XmlNode.prototype.addChildNode = function (child) {
  17. this.children.push(child);
  18. return this;
  19. };
  20. XmlNode.prototype.removeAttribute = function (name) {
  21. delete this.attributes[name];
  22. return this;
  23. };
  24. XmlNode.prototype.toString = function () {
  25. var hasChildren = Boolean(this.children.length);
  26. var xmlText = '<' + this.name;
  27. // add attributes
  28. var attributes = this.attributes;
  29. for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
  30. var attributeName = attributeNames[i];
  31. var attribute = attributes[attributeName];
  32. if (typeof attribute !== 'undefined' && attribute !== null) {
  33. xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
  34. }
  35. }
  36. return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
  37. };
  38. /**
  39. * @api private
  40. */
  41. module.exports = {
  42. XmlNode: XmlNode
  43. };