Files
playlet-piped/playlet-lib/src/source/services/XmlObject.bs
T

133 lines
3.7 KiB
Plaintext

import "pkg:/source/utils/Types.bs"
class XmlObject
private stack = []
private root = invalid
private prolog = []
private INDENT_SIZE = 2
function Node(name as string, attributes = invalid as object) as boolean
newNode = {
type: "node"
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({
type: "text"
text: 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 Comment(comment as string)
if m.stack.count() > 0
m.stack[m.stack.count() - 1].children.push({
type: "comment"
comment: comment
})
else
m.prolog.push({
type: "comment"
comment: comment
})
end if
end function
function ToXmlString() as string
xml = `<?xml version="1.0" encoding="UTF-8"?>\n`
for each item in m.prolog
if item.type = "comment"
xml += `<!-- ${item.comment} -->\n`
end if
end for
xml += m.NodeToXmlString(m.root, 0)
return xml
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]
if i = 0
if child.type <> "text"
xmlString += `\n`
end if
end if
if child.type = "text"
xmlString += m.XmlEscape(child.text)
else if child.type = "comment"
commentIndentString = string((indentLevel + 1) * m.INDENT_SIZE, " ")
xmlString += `${commentIndentString}<!-- ${child.comment} -->\n`
else
xmlString += m.NodeToXmlString(child, indentLevel + 1)
end if
if i = node.children.count() - 1
if child.type <> "text"
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