2025-11-13 13:13:34 -07:00

48 lines
1.5 KiB
JavaScript

import { escapeAttribute } from "./escape-attribute";
import { XmlText } from "./XmlText";
export class XmlNode {
static of(name, childText, withName) {
const node = new XmlNode(name);
if (childText !== undefined) {
node.addChildNode(new XmlText(childText));
}
if (withName !== undefined) {
node.withName(withName);
}
return node;
}
constructor(name, children = []) {
this.name = name;
this.children = children;
this.attributes = {};
}
withName(name) {
this.name = name;
return this;
}
addAttribute(name, value) {
this.attributes[name] = value;
return this;
}
addChildNode(child) {
this.children.push(child);
return this;
}
removeAttribute(name) {
delete this.attributes[name];
return this;
}
toString() {
const hasChildren = Boolean(this.children.length);
let xmlText = `<${this.name}`;
const attributes = this.attributes;
for (const attributeName of Object.keys(attributes)) {
const attribute = attributes[attributeName];
if (typeof attribute !== "undefined" && attribute !== null) {
xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`;
}
}
return (xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}</${this.name}>`);
}
}