xmltree.nim 23 KB

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