Skip to content

Instantly share code, notes, and snippets.

@floydkots
Last active January 28, 2018 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floydkots/41dfb276e2d8488c623b8b01e21ccff4 to your computer and use it in GitHub Desktop.
Save floydkots/41dfb276e2d8488c623b8b01e21ccff4 to your computer and use it in GitHub Desktop.
Simple classes handling an XML Object and XML Tags
class XMLTag {
constructor(name, value) {
this.name = name;
this.value = value;
this.attributes = {}; //List of attributes (objects)
this.children = [];
}
newTag(name, value) {
this.tag = new XMLTag(name, value);
this.children.push(this.tag);
return this.tag;
}
setName(name) {
this.name = name;
}
addAttribute(name, value) {
this.attributes[name] = value;
}
print(level) {
this.attributeString = '';
for (let attribute of Object.entries(this.attributes)) {
this.attributeString += `${attribute[0]}="${attribute[1]}" `;
}
this.string = '\t'.repeat(level) + `<${this.name}`;
if (this.attributeString) {
this.string += ` ${this.attributeString.trim()}>`
} else {
this.string += `>`
}
if (Object.entries(this.attributes).length > 0 || this.children.length > 0) {
this.string += `\n`
}
if (this.value) {
this.string += `${this.value}`
} else if (this.children.length > 0) {
for (let child of this.children) {
this.string += `${child.print(level + 1)}`;
}
}
this.string += `${this.value ? '' : '\t'.repeat(level) }</${this.name}>\n`;
return `${this.string}`;
}
}
class XMLObject {
constructor() {
this.root = new XMLTag()
}
getRoot() {
return this.root;
}
print() {
this.string = '';
if (this.root) {
this.string += `<${this.root.name}>`;
}
if (this.root.children.length > 0) {
this.string += `\n`
}
if (this.root.children.length > 0) {
for (let child of this.root.children) {
this.string += `${child.print(1)}`;
}
}
this.string += `</${this.root.name}>`;
return this.string;
}
}
let x = new XMLObject();
let root = x.getRoot();
root.setName('People');
let person = root.newTag('Person');
person.addAttribute('id', '2323');
person.addAttribute('DOB', '1/1/1901');
let firstName = person.newTag('FirstName', 'John');
let lastName = person.newTag('LastName', 'Smith');
let address = person.newTag('address');
address.newTag('street', '123 NW 45th street');
address.newTag('city', 'Gaithersburg');
address.newTag('zip', '21234');
address.newTag('state', 'MD');
console.log(x.print());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment