fun parseDom()

in runtime/serde/serde-xml/common/src/aws/smithy/kotlin/runtime/serde/xml/dom/XmlNode.kt [61:102]


fun parseDom(reader: XmlStreamReader): XmlNode {

    val nodeStack: ListStack<XmlNode> = mutableListOf()

    loop@while (true) {
        when (val token = reader.nextToken()) {
            is XmlToken.BeginElement -> {
                val newNode = XmlNode.fromToken(token)
                if (nodeStack.isNotEmpty()) {
                    val curr = nodeStack.top()
                    curr.addChild(newNode)
                    newNode.parent = curr
                }

                nodeStack.push(newNode)
            }
            is XmlToken.EndElement -> {
                val curr = nodeStack.top()

                if (curr.name != token.name) {
                    throw DeserializationException("expected end of element: `${curr.name}`, found: `${token.name}`")
                }

                if (nodeStack.count() > 1) {
                    // finished with this child node
                    nodeStack.pop()
                }
            }
            is XmlToken.Text -> {
                val curr = nodeStack.top()
                curr.text = token.value
            }
            null,
            is XmlToken.EndDocument -> break@loop
            else -> continue // ignore unknown token types
        }
    }

    // root node should be all that is left
    check(nodeStack.count() == 1) { "invalid XML document, node stack size > 1" }
    return nodeStack.pop()
}