Files
playlet-piped/playlet-lib/src/source/services/XmlObject.bs
T
2024-04-29 20:20:40 -04:00

107 lines
2.9 KiB
Plaintext

import "pkg:/source/utils/Types.bs"
class XmlObject
private stack = []
private root = invalid
private INDENT_SIZE = 2
function Node(name as string, attributes = invalid as object) as boolean
newNode = {
name: name
attributes: attributes
children: []
}
if m.root = invalid
m.root = newNode
end if
if m.stack.count() > 0
m.stack[m.stack.count() - 1].children.push(newNode)
end if
m.stack.push(newNode)
return true
end function
function Text(text as string)
if m.stack.count() > 0
m.stack[m.stack.count() - 1].children.push(text)
end if
end function
function TextNode(name as string, text as string, attributes = invalid as object)
m.Node(name, attributes)
m.Text(text)
m.End()
end function
function EmptyNode(name as string, attributes = invalid as object)
m.Node(name, attributes)
m.End()
end function
function End()
m.stack.pop()
end function
function ToXmlString() as string
return `<?xml version="1.0" encoding="UTF-8"?>\n` + m.NodeToXmlString(m.root, 0)
end function
function NodeToXmlString(node as object, indentLevel as integer) as string
indentString = string(indentLevel * m.INDENT_SIZE, " ")
xmlString = indentString + "<" + node.name
if node.attributes <> invalid
for each key in node.attributes.keys()
value = m.XmlEscape(`${node.attributes[key]}`)
xmlString += ` ${key}="${value}"`
end for
end if
if node.children.count() = 0
xmlString += ` />\n`
else
xmlString += `>`
for i = 0 to node.children.count() - 1
child = node.children[i]
childIsString = IsString(child)
if i = 0
if not childIsString
xmlString += `\n`
end if
end if
if childIsString
xmlString += m.XmlEscape(child)
else
xmlString += m.NodeToXmlString(child, indentLevel + 1)
end if
if i = node.children.count() - 1
if not childIsString
xmlString += `${indentString}`
end if
end if
end for
xmlString += `</${node.name}>\n`
end if
return xmlString
end function
function XmlEscape(input as string) as string
input = input.replace("&", "&amp;")
input = input.replace("<", "&lt;")
input = input.replace(">", "&gt;")
input = input.replace(`"`, "&quot;")
input = input.replace("'", "&apos;")
return input
end function
end class