Rewrite xmltools.innerText

Make it recursive, define for node types other than xnElement
This commit is contained in:
Dmitry Polienko 2016-11-30 10:38:22 +07:00
commit 6bd86f7543
2 changed files with 35 additions and 9 deletions

View file

@ -91,13 +91,25 @@ proc rawTag*(n: XmlNode): string {.inline.} =
shallowCopy(result, n.fTag) shallowCopy(result, n.fTag)
proc innerText*(n: XmlNode): string = proc innerText*(n: XmlNode): string =
## gets the inner text of `n`. `n` has to be an ``xnElement`` node. Only ## gets the inner text of `n`:
## ``xnText`` and ``xnEntity`` nodes are considered part of `n`'s inner text, ##
## other child nodes are silently ignored. ## - If `n` is `xnText` or `xnEntity`, returns its content.
result = "" ## - If `n` is `xnElement`, runs recursively on each child node and
assert n.k == xnElement ## concatenates the results.
for i in 0 .. n.s.len-1: ## - Otherwise returns an empty string.
if n.s[i].k in {xnText, xnEntity}: result.add(n.s[i].fText) var res = ""
proc worker(n: XmlNode) =
case n.k
of { xnText, xnEntity }:
res.add(n.fText)
of xnElement:
for sub in n.s:
worker(sub)
else:
discard
worker(n)
res
proc tag*(n: XmlNode): string {.inline.} = proc tag*(n: XmlNode): string {.inline.} =
## gets the tag name of `n`. `n` has to be an ``xnElement`` node. ## gets the tag name of `n`. `n` has to be an ``xnElement`` node.

View file

@ -1,6 +1,11 @@
discard """ discard """
file: "txmltree.nim" file: "txmltree.nim"
output: "true" output: '''true
true
true
true
true
'''
""" """
import xmltree, strtabs import xmltree, strtabs
@ -9,5 +14,14 @@ var x = <>a(href="nim.de", newText("www.nim-test.de"))
echo($x == "<a href=\"nim.de\">www.nim-test.de</a>") echo($x == "<a href=\"nim.de\">www.nim-test.de</a>")
echo(newText("foo").innerText == "foo")
echo(newEntity("bar").innerText == "bar")
echo(newComment("baz").innerText == "")
let y = newXmlTree("x", [
newText("foo"),
newXmlTree("y", [
newText("bar")
])
])
echo(y.innerText == "foobar")