xmltree.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## A simple XML tree generator.
  10. ##
  11. runnableExamples:
  12. var g = newElement("myTag")
  13. g.add newText("some text")
  14. g.add newComment("this is comment")
  15. var h = newElement("secondTag")
  16. h.add newEntity("some entity")
  17. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  18. let k = newXmlTree("treeTag", [g, h], att)
  19. doAssert $k == """<treeTag key1="first value" key2="second value">
  20. <myTag>some text<!-- this is comment --></myTag>
  21. <secondTag>&some entity;</secondTag>
  22. </treeTag>"""
  23. ## **See also:**
  24. ## * `xmlparser module <xmlparser.html>`_ for high-level XML parsing
  25. ## * `parsexml module <parsexml.html>`_ for low-level XML parsing
  26. ## * `htmlgen module <htmlgen.html>`_ for html code generator
  27. import std/private/since
  28. import macros, strtabs, strutils
  29. type
  30. XmlNode* = ref XmlNodeObj ## An XML tree consisting of XML nodes.
  31. ##
  32. ## Use `newXmlTree proc <#newXmlTree,string,openArray[XmlNode],XmlAttributes>`_
  33. ## for creating a new tree.
  34. XmlNodeKind* = enum ## Different kinds of XML nodes.
  35. xnText, ## a text element
  36. xnVerbatimText, ##
  37. xnElement, ## an element with 0 or more children
  38. xnCData, ## a CDATA node
  39. xnEntity, ## an entity (like ``&thing;``)
  40. xnComment ## an XML comment
  41. XmlAttributes* = StringTableRef ## An alias for a string to string mapping.
  42. ##
  43. ## Use `toXmlAttributes proc <#toXmlAttributes,varargs[tuple[string,string]]>`_
  44. ## to create `XmlAttributes`.
  45. XmlNodeObj {.acyclic.} = object
  46. case k: XmlNodeKind # private, use the kind() proc to read this field.
  47. of xnText, xnVerbatimText, xnComment, xnCData, xnEntity:
  48. fText: string
  49. of xnElement:
  50. fTag: string
  51. s: seq[XmlNode]
  52. fAttr: XmlAttributes
  53. fClientData: int ## for other clients
  54. const
  55. xmlHeader* = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
  56. ## Header to use for complete XML output.
  57. proc newXmlNode(kind: XmlNodeKind): XmlNode =
  58. ## Creates a new ``XmlNode``.
  59. result = XmlNode(k: kind)
  60. proc newElement*(tag: sink string): XmlNode =
  61. ## Creates a new ``XmlNode`` of kind ``xnElement`` with the given `tag`.
  62. ##
  63. ## See also:
  64. ## * `newXmlTree proc <#newXmlTree,string,openArray[XmlNode],XmlAttributes>`_
  65. ## * [<> macro](#<>.m,untyped)
  66. runnableExamples:
  67. var a = newElement("firstTag")
  68. a.add newElement("childTag")
  69. assert a.kind == xnElement
  70. assert $a == """<firstTag>
  71. <childTag />
  72. </firstTag>"""
  73. result = newXmlNode(xnElement)
  74. result.fTag = tag
  75. result.s = @[]
  76. # init attributes lazily to save memory
  77. proc newText*(text: sink string): XmlNode =
  78. ## Creates a new ``XmlNode`` of kind ``xnText`` with the text `text`.
  79. runnableExamples:
  80. var b = newText("my text")
  81. assert b.kind == xnText
  82. assert $b == "my text"
  83. result = newXmlNode(xnText)
  84. result.fText = text
  85. proc newVerbatimText*(text: sink string): XmlNode {.since: (1, 3).} =
  86. ## Creates a new ``XmlNode`` of kind ``xnVerbatimText`` with the text `text`.
  87. ## **Since**: Version 1.3.
  88. result = newXmlNode(xnVerbatimText)
  89. result.fText = text
  90. proc newComment*(comment: sink string): XmlNode =
  91. ## Creates a new ``XmlNode`` of kind ``xnComment`` with the text `comment`.
  92. runnableExamples:
  93. var c = newComment("my comment")
  94. assert c.kind == xnComment
  95. assert $c == "<!-- my comment -->"
  96. result = newXmlNode(xnComment)
  97. result.fText = comment
  98. proc newCData*(cdata: sink string): XmlNode =
  99. ## Creates a new ``XmlNode`` of kind ``xnCData`` with the text `cdata`.
  100. runnableExamples:
  101. var d = newCData("my cdata")
  102. assert d.kind == xnCData
  103. assert $d == "<![CDATA[my cdata]]>"
  104. result = newXmlNode(xnCData)
  105. result.fText = cdata
  106. proc newEntity*(entity: string): XmlNode =
  107. ## Creates a new ``XmlNode`` of kind ``xnEntity`` with the text `entity`.
  108. runnableExamples:
  109. var e = newEntity("my entity")
  110. assert e.kind == xnEntity
  111. assert $e == "&my entity;"
  112. result = newXmlNode(xnEntity)
  113. result.fText = entity
  114. proc newXmlTree*(tag: sink string, children: openArray[XmlNode],
  115. attributes: XmlAttributes = nil): XmlNode =
  116. ## Creates a new XML tree with `tag`, `children` and `attributes`.
  117. ##
  118. ## See also:
  119. ## * `newElement proc <#newElement,string>`_
  120. ## * [<> macro](#<>.m,untyped)
  121. runnableExamples:
  122. var g = newElement("myTag")
  123. g.add newText("some text")
  124. g.add newComment("this is comment")
  125. var h = newElement("secondTag")
  126. h.add newEntity("some entity")
  127. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  128. let k = newXmlTree("treeTag", [g, h], att)
  129. doAssert $k == """<treeTag key1="first value" key2="second value">
  130. <myTag>some text<!-- this is comment --></myTag>
  131. <secondTag>&some entity;</secondTag>
  132. </treeTag>"""
  133. result = newXmlNode(xnElement)
  134. result.fTag = tag
  135. newSeq(result.s, children.len)
  136. for i in 0..children.len-1: result.s[i] = children[i]
  137. result.fAttr = attributes
  138. proc text*(n: XmlNode): lent string {.inline.} =
  139. ## Gets the associated text with the node `n`.
  140. ##
  141. ## `n` can be a CDATA, Text, comment, or entity node.
  142. ##
  143. ## See also:
  144. ## * `text= proc <#text=,XmlNode,string>`_ for text setter
  145. ## * `tag proc <#tag,XmlNode>`_ for tag getter
  146. ## * `tag= proc <#tag=,XmlNode,string>`_ for tag setter
  147. ## * `innerText proc <#innerText,XmlNode>`_
  148. runnableExamples:
  149. var c = newComment("my comment")
  150. assert $c == "<!-- my comment -->"
  151. assert c.text == "my comment"
  152. assert n.k in {xnText, xnComment, xnCData, xnEntity}
  153. result = n.fText
  154. proc `text=`*(n: XmlNode, text: sink string) {.inline.} =
  155. ## Sets the associated text with the node `n`.
  156. ##
  157. ## `n` can be a CDATA, Text, comment, or entity node.
  158. ##
  159. ## See also:
  160. ## * `text proc <#text,XmlNode>`_ for text getter
  161. ## * `tag proc <#tag,XmlNode>`_ for tag getter
  162. ## * `tag= proc <#tag=,XmlNode,string>`_ for tag setter
  163. runnableExamples:
  164. var e = newEntity("my entity")
  165. assert $e == "&my entity;"
  166. e.text = "a new entity text"
  167. assert $e == "&a new entity text;"
  168. assert n.k in {xnText, xnComment, xnCData, xnEntity}
  169. n.fText = text
  170. proc tag*(n: XmlNode): lent string {.inline.} =
  171. ## Gets the tag name of `n`.
  172. ##
  173. ## `n` has to be an ``xnElement`` node.
  174. ##
  175. ## See also:
  176. ## * `text proc <#text,XmlNode>`_ for text getter
  177. ## * `text= proc <#text=,XmlNode,string>`_ for text setter
  178. ## * `tag= proc <#tag=,XmlNode,string>`_ for tag setter
  179. ## * `innerText proc <#innerText,XmlNode>`_
  180. runnableExamples:
  181. var a = newElement("firstTag")
  182. a.add newElement("childTag")
  183. assert $a == """<firstTag>
  184. <childTag />
  185. </firstTag>"""
  186. assert a.tag == "firstTag"
  187. assert n.k == xnElement
  188. result = n.fTag
  189. proc `tag=`*(n: XmlNode, tag: sink string) {.inline.} =
  190. ## Sets the tag name of `n`.
  191. ##
  192. ## `n` has to be an ``xnElement`` node.
  193. ##
  194. ## See also:
  195. ## * `text proc <#text,XmlNode>`_ for text getter
  196. ## * `text= proc <#text=,XmlNode,string>`_ for text setter
  197. ## * `tag proc <#tag,XmlNode>`_ for tag getter
  198. runnableExamples:
  199. var a = newElement("firstTag")
  200. a.add newElement("childTag")
  201. assert $a == """<firstTag>
  202. <childTag />
  203. </firstTag>"""
  204. a.tag = "newTag"
  205. assert $a == """<newTag>
  206. <childTag />
  207. </newTag>"""
  208. assert n.k == xnElement
  209. n.fTag = tag
  210. proc rawText*(n: XmlNode): string {.inline.} =
  211. ## Returns the underlying 'text' string by reference.
  212. ##
  213. ## This is only used for speed hacks.
  214. when defined(gcDestructors):
  215. result = move(n.fText)
  216. else:
  217. shallowCopy(result, n.fText)
  218. proc rawTag*(n: XmlNode): string {.inline.} =
  219. ## Returns the underlying 'tag' string by reference.
  220. ##
  221. ## This is only used for speed hacks.
  222. when defined(gcDestructors):
  223. result = move(n.fTag)
  224. else:
  225. shallowCopy(result, n.fTag)
  226. proc innerText*(n: XmlNode): string =
  227. ## Gets the inner text of `n`:
  228. ##
  229. ## - If `n` is `xnText` or `xnEntity`, returns its content.
  230. ## - If `n` is `xnElement`, runs recursively on each child node and
  231. ## concatenates the results.
  232. ## - Otherwise returns an empty string.
  233. ##
  234. ## See also:
  235. ## * `text proc <#text,XmlNode>`_
  236. runnableExamples:
  237. var f = newElement("myTag")
  238. f.add newText("my text")
  239. f.add newComment("my comment")
  240. f.add newEntity("my entity")
  241. assert $f == "<myTag>my text<!-- my comment -->&my entity;</myTag>"
  242. assert innerText(f) == "my textmy entity"
  243. proc worker(res: var string, n: XmlNode) =
  244. case n.k
  245. of xnText, xnEntity:
  246. res.add(n.fText)
  247. of xnElement:
  248. for sub in n.s:
  249. worker(res, sub)
  250. else:
  251. discard
  252. result = ""
  253. worker(result, n)
  254. proc add*(father, son: XmlNode) {.inline.} =
  255. ## Adds the child `son` to `father`.
  256. ##
  257. ## See also:
  258. ## * `insert proc <#insert,XmlNode,XmlNode,int>`_
  259. ## * `delete proc <#delete,XmlNode,Natural>`_
  260. runnableExamples:
  261. var f = newElement("myTag")
  262. f.add newText("my text")
  263. f.add newElement("sonTag")
  264. f.add newEntity("my entity")
  265. assert $f == "<myTag>my text<sonTag />&my entity;</myTag>"
  266. add(father.s, son)
  267. proc insert*(father, son: XmlNode, index: int) {.inline.} =
  268. ## Inserts the child `son` to a given position in `father`.
  269. ##
  270. ## `father` and `son` must be of `xnElement` kind.
  271. ##
  272. ## See also:
  273. ## * `add proc <#add,XmlNode,XmlNode>`_
  274. ## * `delete proc <#delete,XmlNode,Natural>`_
  275. runnableExamples:
  276. var f = newElement("myTag")
  277. f.add newElement("first")
  278. f.insert(newElement("second"), 0)
  279. assert $f == """<myTag>
  280. <second />
  281. <first />
  282. </myTag>"""
  283. assert father.k == xnElement and son.k == xnElement
  284. if len(father.s) > index:
  285. insert(father.s, son, index)
  286. else:
  287. insert(father.s, son, len(father.s))
  288. proc delete*(n: XmlNode, i: Natural) =
  289. ## Deletes the `i`'th child of `n`.
  290. ##
  291. ## See also:
  292. ## * `add proc <#add,XmlNode,XmlNode>`_
  293. ## * `insert proc <#insert,XmlNode,XmlNode,int>`_
  294. runnableExamples:
  295. var f = newElement("myTag")
  296. f.add newElement("first")
  297. f.insert(newElement("second"), 0)
  298. f.delete(0)
  299. assert $f == """<myTag>
  300. <first />
  301. </myTag>"""
  302. assert n.k == xnElement
  303. n.s.delete(i)
  304. proc len*(n: XmlNode): int {.inline.} =
  305. ## Returns the number of `n`'s children.
  306. runnableExamples:
  307. var f = newElement("myTag")
  308. f.add newElement("first")
  309. f.insert(newElement("second"), 0)
  310. assert len(f) == 2
  311. if n.k == xnElement: result = len(n.s)
  312. proc kind*(n: XmlNode): XmlNodeKind {.inline.} =
  313. ## Returns `n`'s kind.
  314. runnableExamples:
  315. var a = newElement("firstTag")
  316. assert a.kind == xnElement
  317. var b = newText("my text")
  318. assert b.kind == xnText
  319. result = n.k
  320. proc `[]`*(n: XmlNode, i: int): XmlNode {.inline.} =
  321. ## Returns the `i`'th child of `n`.
  322. runnableExamples:
  323. var f = newElement("myTag")
  324. f.add newElement("first")
  325. f.insert(newElement("second"), 0)
  326. assert $f[1] == "<first />"
  327. assert $f[0] == "<second />"
  328. assert n.k == xnElement
  329. result = n.s[i]
  330. proc `[]`*(n: var XmlNode, i: int): var XmlNode {.inline.} =
  331. ## Returns the `i`'th child of `n` so that it can be modified.
  332. assert n.k == xnElement
  333. result = n.s[i]
  334. proc clear*(n: var XmlNode) =
  335. ## Recursively clears all children of an XmlNode.
  336. ##
  337. runnableExamples:
  338. var g = newElement("myTag")
  339. g.add newText("some text")
  340. g.add newComment("this is comment")
  341. var h = newElement("secondTag")
  342. h.add newEntity("some entity")
  343. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  344. var k = newXmlTree("treeTag", [g, h], att)
  345. doAssert $k == """<treeTag key1="first value" key2="second value">
  346. <myTag>some text<!-- this is comment --></myTag>
  347. <secondTag>&some entity;</secondTag>
  348. </treeTag>"""
  349. clear(k)
  350. doAssert $k == """<treeTag key1="first value" key2="second value" />"""
  351. for i in 0 ..< n.len:
  352. clear(n[i])
  353. if n.k == xnElement:
  354. n.s.setLen(0)
  355. iterator items*(n: XmlNode): XmlNode {.inline.} =
  356. ## Iterates over all direct children of `n`.
  357. runnableExamples:
  358. var g = newElement("myTag")
  359. g.add newText("some text")
  360. g.add newComment("this is comment")
  361. var h = newElement("secondTag")
  362. h.add newEntity("some entity")
  363. g.add h
  364. assert $g == "<myTag>some text<!-- this is comment --><secondTag>&some entity;</secondTag></myTag>"
  365. # for x in g: # the same as `for x in items(g):`
  366. # echo x
  367. # some text
  368. # <!-- this is comment -->
  369. # <secondTag>&some entity;<![CDATA[some cdata]]></secondTag>
  370. assert n.k == xnElement
  371. for i in 0 .. n.len-1: yield n[i]
  372. iterator mitems*(n: var XmlNode): var XmlNode {.inline.} =
  373. ## Iterates over all direct children of `n` so that they can be modified.
  374. assert n.k == xnElement
  375. for i in 0 .. n.len-1: yield n[i]
  376. proc toXmlAttributes*(keyValuePairs: varargs[tuple[key,
  377. val: string]]): XmlAttributes =
  378. ## Converts `{key: value}` pairs into `XmlAttributes`.
  379. ##
  380. runnableExamples:
  381. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  382. var j = newElement("myTag")
  383. j.attrs = att
  384. doAssert $j == """<myTag key1="first value" key2="second value" />"""
  385. newStringTable(keyValuePairs)
  386. proc attrs*(n: XmlNode): XmlAttributes {.inline.} =
  387. ## Gets the attributes belonging to `n`.
  388. ##
  389. ## Returns `nil` if attributes have not been initialised for this node.
  390. ##
  391. ## See also:
  392. ## * `attrs= proc <#attrs=,XmlNode,XmlAttributes>`_ for XmlAttributes setter
  393. ## * `attrsLen proc <#attrsLen,XmlNode>`_ for number of attributes
  394. ## * `attr proc <#attr,XmlNode,string>`_ for finding an attribute
  395. runnableExamples:
  396. var j = newElement("myTag")
  397. assert j.attrs == nil
  398. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  399. j.attrs = att
  400. assert j.attrs == att
  401. assert n.k == xnElement
  402. result = n.fAttr
  403. proc `attrs=`*(n: XmlNode, attr: XmlAttributes) {.inline.} =
  404. ## Sets the attributes belonging to `n`.
  405. ##
  406. ## See also:
  407. ## * `attrs proc <#attrs,XmlNode>`_ for XmlAttributes getter
  408. ## * `attrsLen proc <#attrsLen,XmlNode>`_ for number of attributes
  409. ## * `attr proc <#attr,XmlNode,string>`_ for finding an attribute
  410. runnableExamples:
  411. var j = newElement("myTag")
  412. assert j.attrs == nil
  413. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  414. j.attrs = att
  415. assert j.attrs == att
  416. assert n.k == xnElement
  417. n.fAttr = attr
  418. proc attrsLen*(n: XmlNode): int {.inline.} =
  419. ## Returns the number of `n`'s attributes.
  420. ##
  421. ## See also:
  422. ## * `attrs proc <#attrs,XmlNode>`_ for XmlAttributes getter
  423. ## * `attrs= proc <#attrs=,XmlNode,XmlAttributes>`_ for XmlAttributes setter
  424. ## * `attr proc <#attr,XmlNode,string>`_ for finding an attribute
  425. runnableExamples:
  426. var j = newElement("myTag")
  427. assert j.attrsLen == 0
  428. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  429. j.attrs = att
  430. assert j.attrsLen == 2
  431. assert n.k == xnElement
  432. if not isNil(n.fAttr): result = len(n.fAttr)
  433. proc attr*(n: XmlNode, name: string): string =
  434. ## Finds the first attribute of `n` with a name of `name`.
  435. ## Returns "" on failure.
  436. ##
  437. ## See also:
  438. ## * `attrs proc <#attrs,XmlNode>`_ for XmlAttributes getter
  439. ## * `attrs= proc <#attrs=,XmlNode,XmlAttributes>`_ for XmlAttributes setter
  440. ## * `attrsLen proc <#attrsLen,XmlNode>`_ for number of attributes
  441. runnableExamples:
  442. var j = newElement("myTag")
  443. let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes
  444. j.attrs = att
  445. assert j.attr("key1") == "first value"
  446. assert j.attr("key2") == "second value"
  447. assert n.kind == xnElement
  448. if n.attrs == nil: return ""
  449. return n.attrs.getOrDefault(name)
  450. proc clientData*(n: XmlNode): int {.inline.} =
  451. ## Gets the client data of `n`.
  452. ##
  453. ## The client data field is used by the HTML parser and generator.
  454. result = n.fClientData
  455. proc `clientData=`*(n: XmlNode, data: int) {.inline.} =
  456. ## Sets the client data of `n`.
  457. ##
  458. ## The client data field is used by the HTML parser and generator.
  459. n.fClientData = data
  460. proc addEscaped*(result: var string, s: string) =
  461. ## The same as `result.add(escape(s)) <#escape,string>`_, but more efficient.
  462. for c in items(s):
  463. case c
  464. of '<': result.add("&lt;")
  465. of '>': result.add("&gt;")
  466. of '&': result.add("&amp;")
  467. of '"': result.add("&quot;")
  468. of '\'': result.add("&apos;")
  469. else: result.add(c)
  470. proc escape*(s: string): string =
  471. ## Escapes `s` for inclusion into an XML document.
  472. ##
  473. ## Escapes these characters:
  474. ##
  475. ## ------------ -------------------
  476. ## char is converted to
  477. ## ------------ -------------------
  478. ## ``<`` ``&lt;``
  479. ## ``>`` ``&gt;``
  480. ## ``&`` ``&amp;``
  481. ## ``"`` ``&quot;``
  482. ## ``'`` ``&apos;``
  483. ## ------------ -------------------
  484. ##
  485. ## You can also use `addEscaped proc <#addEscaped,string,string>`_.
  486. result = newStringOfCap(s.len)
  487. addEscaped(result, s)
  488. proc addIndent(result: var string, indent: int, addNewLines: bool) =
  489. if addNewLines:
  490. result.add("\n")
  491. for i in 1 .. indent:
  492. result.add(' ')
  493. proc add*(result: var string, n: XmlNode, indent = 0, indWidth = 2,
  494. addNewLines = true) =
  495. ## Adds the textual representation of `n` to string `result`.
  496. runnableExamples:
  497. var
  498. a = newElement("firstTag")
  499. b = newText("my text")
  500. c = newComment("my comment")
  501. s = ""
  502. s.add(c)
  503. s.add(a)
  504. s.add(b)
  505. assert s == "<!-- my comment --><firstTag />my text"
  506. proc noWhitespace(n: XmlNode): bool =
  507. for i in 0 ..< n.len:
  508. if n[i].kind in {xnText, xnEntity}: return true
  509. proc addEscapedAttr(result: var string, s: string) =
  510. # `addEscaped` alternative with less escaped characters.
  511. # Only to be used for escaping attribute values enclosed in double quotes!
  512. for c in items(s):
  513. case c
  514. of '<': result.add("&lt;")
  515. of '>': result.add("&gt;")
  516. of '&': result.add("&amp;")
  517. of '"': result.add("&quot;")
  518. else: result.add(c)
  519. if n == nil: return
  520. case n.k
  521. of xnElement:
  522. if indent > 0:
  523. result.addIndent(indent, addNewLines)
  524. let
  525. addNewLines = if n.noWhitespace():
  526. false
  527. else:
  528. addNewLines
  529. result.add('<')
  530. result.add(n.fTag)
  531. if not isNil(n.fAttr):
  532. for key, val in pairs(n.fAttr):
  533. result.add(' ')
  534. result.add(key)
  535. result.add("=\"")
  536. result.addEscapedAttr(val)
  537. result.add('"')
  538. if n.len == 0:
  539. result.add(" />")
  540. return
  541. let
  542. indentNext = if n.noWhitespace():
  543. indent
  544. else:
  545. indent+indWidth
  546. result.add('>')
  547. for i in 0 ..< n.len:
  548. result.add(n[i], indentNext, indWidth, addNewLines)
  549. if not n.noWhitespace():
  550. result.addIndent(indent, addNewLines)
  551. result.add("</")
  552. result.add(n.fTag)
  553. result.add(">")
  554. of xnText:
  555. result.addEscaped(n.fText)
  556. of xnVerbatimText:
  557. result.add(n.fText)
  558. of xnComment:
  559. result.add("<!-- ")
  560. result.addEscaped(n.fText)
  561. result.add(" -->")
  562. of xnCData:
  563. result.add("<![CDATA[")
  564. result.add(n.fText)
  565. result.add("]]>")
  566. of xnEntity:
  567. result.add('&')
  568. result.add(n.fText)
  569. result.add(';')
  570. proc `$`*(n: XmlNode): string =
  571. ## Converts `n` into its string representation.
  572. ##
  573. ## No ``<$xml ...$>`` declaration is produced, so that the produced
  574. ## XML fragments are composable.
  575. result = ""
  576. result.add(n)
  577. proc child*(n: XmlNode, name: string): XmlNode =
  578. ## Finds the first child element of `n` with a name of `name`.
  579. ## Returns `nil` on failure.
  580. runnableExamples:
  581. var f = newElement("myTag")
  582. f.add newElement("firstSon")
  583. f.add newElement("secondSon")
  584. f.add newElement("thirdSon")
  585. assert $(f.child("secondSon")) == "<secondSon />"
  586. assert n.kind == xnElement
  587. for i in items(n):
  588. if i.kind == xnElement:
  589. if i.tag == name:
  590. return i
  591. proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode],
  592. caseInsensitive = false) =
  593. ## Iterates over all the children of `n` returning those matching `tag`.
  594. ##
  595. ## Found nodes satisfying the condition will be appended to the `result`
  596. ## sequence.
  597. runnableExamples:
  598. var
  599. b = newElement("good")
  600. c = newElement("bad")
  601. d = newElement("BAD")
  602. e = newElement("GOOD")
  603. b.add newText("b text")
  604. c.add newText("c text")
  605. d.add newText("d text")
  606. e.add newText("e text")
  607. let a = newXmlTree("father", [b, c, d, e])
  608. var s = newSeq[XmlNode]()
  609. a.findAll("good", s)
  610. assert $s == "@[<good>b text</good>]"
  611. s.setLen(0)
  612. a.findAll("good", s, caseInsensitive = true)
  613. assert $s == "@[<good>b text</good>, <GOOD>e text</GOOD>]"
  614. s.setLen(0)
  615. a.findAll("BAD", s)
  616. assert $s == "@[<BAD>d text</BAD>]"
  617. s.setLen(0)
  618. a.findAll("BAD", s, caseInsensitive = true)
  619. assert $s == "@[<bad>c text</bad>, <BAD>d text</BAD>]"
  620. assert n.k == xnElement
  621. for child in n.items():
  622. if child.k != xnElement:
  623. continue
  624. if child.tag == tag or
  625. (caseInsensitive and cmpIgnoreCase(child.tag, tag) == 0):
  626. result.add(child)
  627. child.findAll(tag, result)
  628. proc findAll*(n: XmlNode, tag: string, caseInsensitive = false): seq[XmlNode] =
  629. ## A shortcut version to assign in let blocks.
  630. runnableExamples:
  631. var
  632. b = newElement("good")
  633. c = newElement("bad")
  634. d = newElement("BAD")
  635. e = newElement("GOOD")
  636. b.add newText("b text")
  637. c.add newText("c text")
  638. d.add newText("d text")
  639. e.add newText("e text")
  640. let a = newXmlTree("father", [b, c, d, e])
  641. assert $(a.findAll("good")) == "@[<good>b text</good>]"
  642. assert $(a.findAll("BAD")) == "@[<BAD>d text</BAD>]"
  643. assert $(a.findAll("good", caseInsensitive = true)) == "@[<good>b text</good>, <GOOD>e text</GOOD>]"
  644. assert $(a.findAll("BAD", caseInsensitive = true)) == "@[<bad>c text</bad>, <BAD>d text</BAD>]"
  645. newSeq(result, 0)
  646. findAll(n, tag, result, caseInsensitive)
  647. proc xmlConstructor(a: NimNode): NimNode =
  648. if a.kind == nnkCall:
  649. result = newCall("newXmlTree", toStrLit(a[0]))
  650. var attrs = newNimNode(nnkBracket, a)
  651. var newStringTabCall = newCall(bindSym"newStringTable", attrs,
  652. bindSym"modeCaseSensitive")
  653. var elements = newNimNode(nnkBracket, a)
  654. for i in 1..a.len-1:
  655. if a[i].kind == nnkExprEqExpr:
  656. # In order to support attributes like `data-lang` we have to
  657. # replace whitespace because `toStrLit` gives `data - lang`.
  658. let attrName = toStrLit(a[i][0]).strVal.replace(" ", "")
  659. attrs.add(newStrLitNode(attrName))
  660. attrs.add(a[i][1])
  661. #echo repr(attrs)
  662. else:
  663. elements.add(a[i])
  664. result.add(elements)
  665. if attrs.len > 1:
  666. #echo repr(newStringTabCall)
  667. result.add(newStringTabCall)
  668. else:
  669. result = newCall("newXmlTree", toStrLit(a))
  670. macro `<>`*(x: untyped): untyped =
  671. ## Constructor macro for XML. Example usage:
  672. ##
  673. ## .. code-block:: nim
  674. ## <>a(href="http://nim-lang.org", newText("Nim rules."))
  675. ##
  676. ## Produces an XML tree for::
  677. ##
  678. ## <a href="http://nim-lang.org">Nim rules.</a>
  679. ##
  680. result = xmlConstructor(x)