added a nicer subscript navigation of DOM kinda like jquery but without the $ :)

This commit is contained in:
James Strachan
2012-02-24 17:45:43 +00:00
parent 6bee965c51
commit 5841438134
2 changed files with 27 additions and 10 deletions
+22 -8
View File
@@ -74,22 +74,36 @@ set(value) {
// Helper methods
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Document?.get(selector: String): List<Element> {
val root = this?.getDocumentElement()
return if (root != null) {
root.get(selector)
} else {
Collections.EMPTY_LIST as List<Element>
}
}
/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
fun Element.get(selector: String): List<Element> {
if (selector.startsWith(".")) {
// TODO filter by CSS style class
} else if (selector.startsWith("#")) {
// TODO lookup by ID
}
// TODO assume its a vanilla element name
return this.getElementsByTagName(selector).toElementList()
}
/** Returns the children of the element as a list */
inline fun Element?.children(): List<Node> {
return this?.getChildNodes().toList()
}
inline fun Element?.elementsByTagName(name: String?): List<Element> {
return this?.getElementsByTagName(name).toElementList()
}
inline fun Element?.elementsByTagNameNS(namespaceUri: String?, localName: String?): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
}
inline fun Document?.elementsByTagName(name: String?): List<Element> {
return this?.getElementsByTagName(name).toElementList()
}
inline fun Document?.elementsByTagNameNS(namespaceUri: String?, localName: String?): List<Element> {
return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList()
}
+5 -2
View File
@@ -11,6 +11,10 @@ class DomBuilderTest() : TestSupport() {
fun testBuildDocument() {
var doc = createDocument()
assert {
doc["grandchild"].isEmpty()
}
doc.addElement("foo") {
id = "id1"
style = "bold"
@@ -27,8 +31,7 @@ class DomBuilderTest() : TestSupport() {
}
println("builder document: ${doc.toXmlString()}")
val grandChild = doc.elementsByTagName("grandChild").first
val grandChild = doc["grandChild"].first
if (grandChild != null) {
println("got element ${grandChild.toXmlString()} with text '${grandChild.text}`")
assertEquals("Hello World!", grandChild.text)