Skip to content

Instantly share code, notes, and snippets.

@vorobeij
Created April 8, 2023 11:34
Show Gist options
  • Save vorobeij/f6d63b2c6c8e829a86ee3530cae71e23 to your computer and use it in GitHub Desktop.
Save vorobeij/f6d63b2c6c8e829a86ee3530cae71e23 to your computer and use it in GitHub Desktop.
Parse xml
package au.suby.data.api.youtube.wrappers
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
@Suppress("unused")
class XmlParser {
fun <T> parse(
xmlDoc: Document,
tag: String,
visitor: ((node: Element, attributes: Map<String, String>) -> T)
): List<T> {
val nodes: NodeList = xmlDoc.getElementsByTagName(tag)
val objects = arrayListOf<T>()
for (i in 0 until nodes.length) {
val node: Node = nodes.item(i)
if (node.nodeType == Node.ELEMENT_NODE) {
val elem = node as Element
val attributes = mutableMapOf<String, String>()
for (j in 0 until elem.attributes.length) {
attributes.putIfAbsentt(
elem.attributes.item(j).nodeName,
elem.attributes.item(j).nodeValue
)
}
objects.add(visitor(node, attributes))
}
}
return objects
}
fun <T> parse(
xmlDoc: Node,
visitor: ((node: Element, attributes: Map<String, String>) -> T)
): List<T> {
val nodes: NodeList = xmlDoc.childNodes
val objects = arrayListOf<T>()
for (i in 0 until nodes.length) {
val node: Node = nodes.item(i)
if (node.nodeType == Node.ELEMENT_NODE) {
val elem = node as Element
val attributes = mutableMapOf<String, String>()
for (j in 0 until elem.attributes.length) {
attributes.putIfAbsentt(
elem.attributes.item(j).nodeName,
elem.attributes.item(j).nodeValue
)
}
objects.add(visitor(node, attributes))
}
}
return objects
}
private fun <K, V> MutableMap<K, V>.putIfAbsentt(key: K, value: V): V? {
var v: V? = get(key)
if (v == null) {
v = put(key, value)
}
return v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment