From 6bd86f7543ba0ab7d40764a206fdd5183ce8eb88 Mon Sep 17 00:00:00 2001 From: Dmitry Polienko Date: Wed, 30 Nov 2016 10:38:22 +0700 Subject: Rewrite xmltools.innerText Make it recursive, define for node types other than xnElement --- lib/pure/xmltree.nim | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'lib/pure') diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim index 3c6eb14e3..5385705cd 100644 --- a/lib/pure/xmltree.nim +++ b/lib/pure/xmltree.nim @@ -91,13 +91,25 @@ proc rawTag*(n: XmlNode): string {.inline.} = shallowCopy(result, n.fTag) proc innerText*(n: XmlNode): string = - ## gets the inner text of `n`. `n` has to be an ``xnElement`` node. Only - ## ``xnText`` and ``xnEntity`` nodes are considered part of `n`'s inner text, - ## other child nodes are silently ignored. - result = "" - assert n.k == xnElement - for i in 0 .. n.s.len-1: - if n.s[i].k in {xnText, xnEntity}: result.add(n.s[i].fText) + ## gets the inner text of `n`: + ## + ## - If `n` is `xnText` or `xnEntity`, returns its content. + ## - If `n` is `xnElement`, runs recursively on each child node and + ## concatenates the results. + ## - Otherwise returns an empty string. + 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.} = ## gets the tag name of `n`. `n` has to be an ``xnElement`` node. -- cgit 1.4.1-2-gfad0 From ff69656f80a6494eecad3bd41e9c1d8e68e7f5b7 Mon Sep 17 00:00:00 2001 From: Dmitry Polienko Date: Thu, 1 Dec 2016 09:14:14 +0700 Subject: Clean up (as suggested by @Araq) --- lib/pure/xmltree.nim | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'lib/pure') diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim index 5385705cd..7cfb62157 100644 --- a/lib/pure/xmltree.nim +++ b/lib/pure/xmltree.nim @@ -97,19 +97,18 @@ proc innerText*(n: XmlNode): string = ## - If `n` is `xnElement`, runs recursively on each child node and ## concatenates the results. ## - Otherwise returns an empty string. - var res = "" - proc worker(n: XmlNode) = + proc worker(res: var string, n: XmlNode) = case n.k - of { xnText, xnEntity }: + of xnText, xnEntity: res.add(n.fText) of xnElement: for sub in n.s: - worker(sub) + worker(res, sub) else: discard - worker(n) - res + result = "" + worker(result, n) proc tag*(n: XmlNode): string {.inline.} = ## gets the tag name of `n`. `n` has to be an ``xnElement`` node. -- cgit 1.4.1-2-gfad0