xml.el 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. ;;; xml.el --- XML parser -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2000-2017 Free Software Foundation, Inc.
  3. ;; Author: Emmanuel Briot <briot@gnat.com>
  4. ;; Maintainer: Mark A. Hershberger <mah@everybody.org>
  5. ;; Keywords: xml, data
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; This file contains a somewhat incomplete non-validating XML parser. It
  19. ;; parses a file, and returns a list that can be used internally by
  20. ;; any other Lisp libraries.
  21. ;;; FILE FORMAT
  22. ;; The document type declaration may either be ignored or (optionally)
  23. ;; parsed, but currently the parsing will only accept element
  24. ;; declarations. The XML file is assumed to be well-formed. In case
  25. ;; of error, the parsing stops and the XML file is shown where the
  26. ;; parsing stopped.
  27. ;;
  28. ;; It also knows how to ignore comments and processing instructions.
  29. ;;
  30. ;; The XML file should have the following format:
  31. ;; <node1 attr1="name1" attr2="name2" ...>value
  32. ;; <node2 attr3="name3" attr4="name4">value2</node2>
  33. ;; <node3 attr5="name5" attr6="name6">value3</node3>
  34. ;; </node1>
  35. ;; Of course, the name of the nodes and attributes can be anything. There can
  36. ;; be any number of attributes (or none), as well as any number of children
  37. ;; below the nodes.
  38. ;;
  39. ;; There can be only top level node, but with any number of children below.
  40. ;;; LIST FORMAT
  41. ;; The functions `xml-parse-file', `xml-parse-region' and
  42. ;; `xml-parse-tag' return a list with the following format:
  43. ;;
  44. ;; xml-list ::= (node node ...)
  45. ;; node ::= (qname attribute-list . child_node_list)
  46. ;; child_node_list ::= child_node child_node ...
  47. ;; child_node ::= node | string
  48. ;; qname ::= (:namespace-uri . "name") | "name"
  49. ;; attribute_list ::= ((qname . "value") (qname . "value") ...)
  50. ;; | nil
  51. ;; string ::= "..."
  52. ;;
  53. ;; Some macros are provided to ease the parsing of this list.
  54. ;; Whitespace is preserved. Fixme: There should be a tree-walker that
  55. ;; can remove it.
  56. ;; TODO:
  57. ;; * xml:base, xml:space support
  58. ;; * more complete DOCTYPE parsing
  59. ;; * pi support
  60. ;;; Code:
  61. ;; Note that buffer-substring and match-string were formerly used in
  62. ;; several places, because the -no-properties variants remove
  63. ;; composition info. However, after some discussion on emacs-devel,
  64. ;; the consensus was that the speed of the -no-properties variants was
  65. ;; a worthwhile tradeoff especially since we're usually parsing files
  66. ;; instead of hand-crafted XML.
  67. ;;; Macros to parse the list
  68. (defconst xml-undefined-entity "?"
  69. "What to substitute for undefined entities")
  70. (defconst xml-default-ns '(("" . "")
  71. ("xml" . "http://www.w3.org/XML/1998/namespace")
  72. ("xmlns" . "http://www.w3.org/2000/xmlns/"))
  73. "Alist mapping default XML namespaces to their URIs.")
  74. (defvar xml-entity-alist
  75. '(("lt" . "&#60;")
  76. ("gt" . ">")
  77. ("apos" . "'")
  78. ("quot" . "\"")
  79. ("amp" . "&#38;"))
  80. "Alist mapping XML entities to their replacement text.")
  81. (defvar xml-entity-expansion-limit 20000
  82. "The maximum size of entity reference expansions.
  83. If the size of the buffer increases by this many characters while
  84. expanding entity references in a segment of character data, the
  85. XML parser signals an error. Setting this to nil removes the
  86. limit (making the parser vulnerable to XML bombs).")
  87. (defvar xml-parameter-entity-alist nil
  88. "Alist of defined XML parametric entities.")
  89. (defvar xml-sub-parser nil
  90. "Non-nil when the XML parser is parsing an XML fragment.")
  91. (defvar xml-validating-parser nil
  92. "Set to non-nil to get validity checking.")
  93. (defsubst xml-node-name (node)
  94. "Return the tag associated with NODE.
  95. Without namespace-aware parsing, the tag is a symbol.
  96. With namespace-aware parsing, the tag is a cons of a string
  97. representing the uri of the namespace with the local name of the
  98. tag. For example,
  99. <foo>
  100. would be represented by
  101. (\"\" . \"foo\").
  102. If you'd just like a plain symbol instead, use `symbol-qnames' in
  103. the PARSE-NS argument."
  104. (car node))
  105. (defsubst xml-node-attributes (node)
  106. "Return the list of attributes of NODE.
  107. The list can be nil."
  108. (nth 1 node))
  109. (defsubst xml-node-children (node)
  110. "Return the list of children of NODE.
  111. This is a list of nodes, and it can be nil."
  112. (cddr node))
  113. (defun xml-get-children (node child-name)
  114. "Return the children of NODE whose tag is CHILD-NAME.
  115. CHILD-NAME should match the value returned by `xml-node-name'."
  116. (let ((match ()))
  117. (dolist (child (xml-node-children node))
  118. (if (and (listp child)
  119. (equal (xml-node-name child) child-name))
  120. (push child match)))
  121. (nreverse match)))
  122. (defun xml-get-attribute-or-nil (node attribute)
  123. "Get from NODE the value of ATTRIBUTE.
  124. Return nil if the attribute was not found.
  125. See also `xml-get-attribute'."
  126. (cdr (assoc attribute (xml-node-attributes node))))
  127. (defsubst xml-get-attribute (node attribute)
  128. "Get from NODE the value of ATTRIBUTE.
  129. An empty string is returned if the attribute was not found.
  130. See also `xml-get-attribute-or-nil'."
  131. (or (xml-get-attribute-or-nil node attribute) ""))
  132. ;;; Regular expressions for XML components
  133. ;; The following regexps are used as subexpressions in regexps that
  134. ;; are `eval-when-compile'd for efficiency, so they must be defined at
  135. ;; compile time.
  136. (eval-and-compile
  137. ;; [4] NameStartChar
  138. ;; See the definition of word syntax in `xml-syntax-table'.
  139. (defconst xml-name-start-char-re (concat "[[:word:]:_]"))
  140. ;; [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7
  141. ;; | [#x0300-#x036F] | [#x203F-#x2040]
  142. (defconst xml-name-char-re (concat "[-0-9.[:word:]:_·̀-ͯ‿-⁀]"))
  143. ;; [5] Name ::= NameStartChar (NameChar)*
  144. (defconst xml-name-re (concat xml-name-start-char-re xml-name-char-re "*"))
  145. ;; [6] Names ::= Name (#x20 Name)*
  146. (defconst xml-names-re (concat xml-name-re "\\(?: " xml-name-re "\\)*"))
  147. ;; [7] Nmtoken ::= (NameChar)+
  148. (defconst xml-nmtoken-re (concat xml-name-char-re "+"))
  149. ;; [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
  150. (defconst xml-nmtokens-re (concat xml-nmtoken-re "\\(?: " xml-name-re "\\)*"))
  151. ;; [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
  152. (defconst xml-char-ref-re "\\(?:&#[0-9]+;\\|&#x[0-9a-fA-F]+;\\)")
  153. ;; [68] EntityRef ::= '&' Name ';'
  154. (defconst xml-entity-ref (concat "&" xml-name-re ";"))
  155. (defconst xml-entity-or-char-ref-re (concat "&\\(?:#\\(x\\)?\\([0-9a-fA-F]+\\)\\|\\("
  156. xml-name-re "\\)\\);"))
  157. ;; [69] PEReference ::= '%' Name ';'
  158. (defconst xml-pe-reference-re (concat "%\\(" xml-name-re "\\);"))
  159. ;; [67] Reference ::= EntityRef | CharRef
  160. (defconst xml-reference-re (concat "\\(?:" xml-entity-ref "\\|" xml-char-ref-re "\\)"))
  161. ;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
  162. ;; | "'" ([^<&'] | Reference)* "'"
  163. (defconst xml-att-value-re (concat "\\(?:\"\\(?:[^&\"]\\|"
  164. xml-reference-re "\\)*\"\\|"
  165. "'\\(?:[^&']\\|" xml-reference-re
  166. "\\)*'\\)"))
  167. ;; [56] TokenizedType ::= 'ID'
  168. ;; [VC: ID] [VC: One ID / Element Type] [VC: ID Attribute Default]
  169. ;; | 'IDREF' [VC: IDREF]
  170. ;; | 'IDREFS' [VC: IDREF]
  171. ;; | 'ENTITY' [VC: Entity Name]
  172. ;; | 'ENTITIES' [VC: Entity Name]
  173. ;; | 'NMTOKEN' [VC: Name Token]
  174. ;; | 'NMTOKENS' [VC: Name Token]
  175. (defconst xml-tokenized-type-re (concat "\\(?:ID\\|IDREF\\|IDREFS\\|ENTITY\\|"
  176. "ENTITIES\\|NMTOKEN\\|NMTOKENS\\)"))
  177. ;; [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
  178. (defconst xml-notation-type-re
  179. (concat "\\(?:NOTATION\\s-+(\\s-*" xml-name-re
  180. "\\(?:\\s-*|\\s-*" xml-name-re "\\)*\\s-*)\\)"))
  181. ;; [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
  182. ;; [VC: Enumeration] [VC: No Duplicate Tokens]
  183. (defconst xml-enumeration-re (concat "\\(?:(\\s-*" xml-nmtoken-re
  184. "\\(?:\\s-*|\\s-*" xml-nmtoken-re
  185. "\\)*\\s-+)\\)"))
  186. ;; [57] EnumeratedType ::= NotationType | Enumeration
  187. (defconst xml-enumerated-type-re (concat "\\(?:" xml-notation-type-re
  188. "\\|" xml-enumeration-re "\\)"))
  189. ;; [54] AttType ::= StringType | TokenizedType | EnumeratedType
  190. ;; [55] StringType ::= 'CDATA'
  191. (defconst xml-att-type-re (concat "\\(?:CDATA\\|" xml-tokenized-type-re
  192. "\\|" xml-notation-type-re
  193. "\\|" xml-enumerated-type-re "\\)"))
  194. ;; [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
  195. (defconst xml-default-decl-re (concat "\\(?:#REQUIRED\\|#IMPLIED\\|"
  196. "\\(?:#FIXED\\s-+\\)*"
  197. xml-att-value-re "\\)"))
  198. ;; [53] AttDef ::= S Name S AttType S DefaultDecl
  199. (defconst xml-att-def-re (concat "\\(?:\\s-*" xml-name-re
  200. "\\s-*" xml-att-type-re
  201. "\\s-*" xml-default-decl-re "\\)"))
  202. ;; [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
  203. ;; | "'" ([^%&'] | PEReference | Reference)* "'"
  204. (defconst xml-entity-value-re (concat "\\(?:\"\\(?:[^%&\"]\\|"
  205. xml-pe-reference-re
  206. "\\|" xml-reference-re
  207. "\\)*\"\\|'\\(?:[^%&']\\|"
  208. xml-pe-reference-re "\\|"
  209. xml-reference-re "\\)*'\\)"))
  210. ) ; End of `eval-when-compile'
  211. ;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
  212. ;; | 'PUBLIC' S PubidLiteral S SystemLiteral
  213. ;; [76] NDataDecl ::= S 'NDATA' S
  214. ;; [73] EntityDef ::= EntityValue| (ExternalID NDataDecl?)
  215. ;; [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
  216. ;; [74] PEDef ::= EntityValue | ExternalID
  217. ;; [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
  218. ;; [70] EntityDecl ::= GEDecl | PEDecl
  219. ;; Note that this is setup so that we can do whitespace-skipping with
  220. ;; `(skip-syntax-forward " ")', inter alia. Previously this was slow
  221. ;; compared with `re-search-forward', but that has been fixed.
  222. (defvar xml-syntax-table
  223. ;; By default, characters have symbol syntax.
  224. (let ((table (make-char-table 'syntax-table '(3))))
  225. ;; The XML space chars [3], and nothing else, have space syntax.
  226. (dolist (c '(?\s ?\t ?\r ?\n))
  227. (modify-syntax-entry c " " table))
  228. ;; The characters in NameStartChar [4], aside from ':' and '_',
  229. ;; have word syntax. This is used by `xml-name-start-char-re'.
  230. (modify-syntax-entry '(?A . ?Z) "w" table)
  231. (modify-syntax-entry '(?a . ?z) "w" table)
  232. (modify-syntax-entry '(#xC0 . #xD6) "w" table)
  233. (modify-syntax-entry '(#xD8 . #XF6) "w" table)
  234. (modify-syntax-entry '(#xF8 . #X2FF) "w" table)
  235. (modify-syntax-entry '(#x370 . #X37D) "w" table)
  236. (modify-syntax-entry '(#x37F . #x1FFF) "w" table)
  237. (modify-syntax-entry '(#x200C . #x200D) "w" table)
  238. (modify-syntax-entry '(#x2070 . #x218F) "w" table)
  239. (modify-syntax-entry '(#x2C00 . #x2FEF) "w" table)
  240. (modify-syntax-entry '(#x3001 . #xD7FF) "w" table)
  241. (modify-syntax-entry '(#xF900 . #xFDCF) "w" table)
  242. (modify-syntax-entry '(#xFDF0 . #xFFFD) "w" table)
  243. (modify-syntax-entry '(#x10000 . #xEFFFF) "w" table)
  244. table)
  245. "Syntax table used by the XML parser.
  246. In this syntax table, the XML space characters [ \\t\\r\\n], and
  247. only those characters, have whitespace syntax.")
  248. ;;; Entry points:
  249. ;;;###autoload
  250. (defun xml-parse-file (file &optional parse-dtd parse-ns)
  251. "Parse the well-formed XML file FILE.
  252. Return the top node with all its children.
  253. If PARSE-DTD is non-nil, the DTD is parsed rather than skipped.
  254. If PARSE-NS is non-nil, then QNAMES are expanded. By default,
  255. the variable `xml-default-ns' is the mapping from namespaces to
  256. URIs, and expanded names will be returned as a cons
  257. (\"namespace:\" . \"foo\").
  258. If PARSE-NS is an alist, it will be used as the mapping from
  259. namespace to URIs instead.
  260. If it is the symbol `symbol-qnames', expanded names will be
  261. returned as a plain symbol `namespace:foo' instead of a cons.
  262. Both features can be combined by providing a cons cell
  263. (symbol-qnames . ALIST)."
  264. (with-temp-buffer
  265. (insert-file-contents file)
  266. (xml--parse-buffer parse-dtd parse-ns)))
  267. ;;;###autoload
  268. (defun xml-parse-region (&optional beg end buffer parse-dtd parse-ns)
  269. "Parse the region from BEG to END in BUFFER.
  270. Return the XML parse tree, or raise an error if the region does
  271. not contain well-formed XML.
  272. If BEG is nil, it defaults to `point-min'.
  273. If END is nil, it defaults to `point-max'.
  274. If BUFFER is nil, it defaults to the current buffer.
  275. If PARSE-DTD is non-nil, parse the DTD and return it as the first
  276. element of the list.
  277. If PARSE-NS is non-nil, then QNAMES are expanded. By default,
  278. the variable `xml-default-ns' is the mapping from namespaces to
  279. URIs, and expanded names will be returned as a cons
  280. (\"namespace:\" . \"foo\").
  281. If PARSE-NS is an alist, it will be used as the mapping from
  282. namespace to URIs instead.
  283. If it is the symbol `symbol-qnames', expanded names will be
  284. returned as a plain symbol `namespace:foo' instead of a cons.
  285. Both features can be combined by providing a cons cell
  286. (symbol-qnames . ALIST)."
  287. ;; Use fixed syntax table to ensure regexp char classes and syntax
  288. ;; specs DTRT.
  289. (unless buffer
  290. (setq buffer (current-buffer)))
  291. (with-temp-buffer
  292. (insert-buffer-substring-no-properties buffer beg end)
  293. (xml--parse-buffer parse-dtd parse-ns)))
  294. ;; XML [5]
  295. ;; Fixme: This needs re-writing to deal with the XML grammar properly, i.e.
  296. ;; document ::= prolog element Misc*
  297. ;; prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
  298. (defun xml--parse-buffer (parse-dtd parse-ns)
  299. (with-syntax-table xml-syntax-table
  300. (let ((case-fold-search nil) ; XML is case-sensitive.
  301. ;; Prevent entity definitions from changing the defaults
  302. (xml-entity-alist xml-entity-alist)
  303. (xml-parameter-entity-alist xml-parameter-entity-alist)
  304. xml result dtd)
  305. (goto-char (point-min))
  306. (while (not (eobp))
  307. (if (search-forward "<" nil t)
  308. (progn
  309. (forward-char -1)
  310. (setq result (xml-parse-tag-1 parse-dtd parse-ns))
  311. (cond
  312. ((null result)
  313. ;; Not looking at an xml start tag.
  314. (unless (eobp)
  315. (forward-char 1)))
  316. ((and xml (not xml-sub-parser))
  317. ;; Translation of rule [1] of XML specifications
  318. (error "XML: (Not Well-Formed) Only one root tag allowed"))
  319. ((and (listp (car result))
  320. parse-dtd)
  321. (setq dtd (car result))
  322. (if (cdr result) ; possible leading comment
  323. (push (cdr result) xml)))
  324. (t
  325. (push result xml))))
  326. (goto-char (point-max))))
  327. (if parse-dtd
  328. (cons dtd (nreverse xml))
  329. (nreverse xml)))))
  330. (defun xml-maybe-do-ns (name default xml-ns)
  331. "Perform any namespace expansion.
  332. NAME is the name to perform the expansion on.
  333. DEFAULT is the default namespace. XML-NS is a cons of namespace
  334. names to uris. When namespace-aware parsing is off, then XML-NS
  335. is nil.
  336. During namespace-aware parsing, any name without a namespace is
  337. put into the namespace identified by DEFAULT. nil is used to
  338. specify that the name shouldn't be given a namespace.
  339. Expanded names will by default be returned as a cons. If you
  340. would like to get plain symbols instead, provide a cons cell
  341. (symbol-qnames . ALIST)
  342. in the XML-NS argument."
  343. (if (consp xml-ns)
  344. (let* ((symbol-qnames (eq (car-safe xml-ns) 'symbol-qnames))
  345. (nsp (string-match ":" name))
  346. (lname (if nsp (substring name (match-end 0)) name))
  347. (prefix (if nsp (substring name 0 (match-beginning 0)) default))
  348. (special (and (string-equal lname "xmlns") (not prefix)))
  349. ;; Setting default to nil will insure that there is not
  350. ;; matching cons in xml-ns. In which case we
  351. (ns (or (cdr (assoc (if special "xmlns" prefix)
  352. (if symbol-qnames (cdr xml-ns) xml-ns)))
  353. "")))
  354. (if (and symbol-qnames
  355. (not special)
  356. (not (string= prefix "xmlns")))
  357. (intern (concat ns lname))
  358. (cons ns (if special "" lname))))
  359. (intern name)))
  360. (defun xml-parse-tag (&optional parse-dtd parse-ns)
  361. "Parse the tag at point.
  362. If PARSE-DTD is non-nil, the DTD of the document, if any, is parsed and
  363. returned as the first element in the list.
  364. If PARSE-NS is non-nil, expand QNAMES; for further details, see
  365. `xml-parse-region'.
  366. Return one of:
  367. - a list : the matching node
  368. - nil : the point is not looking at a tag.
  369. - a pair : the first element is the DTD, the second is the node."
  370. (let* ((case-fold-search nil)
  371. ;; Prevent entity definitions from changing the defaults
  372. (xml-entity-alist xml-entity-alist)
  373. (xml-parameter-entity-alist xml-parameter-entity-alist)
  374. (buf (current-buffer))
  375. (pos (point)))
  376. (with-temp-buffer
  377. (with-syntax-table xml-syntax-table
  378. (insert-buffer-substring-no-properties buf pos)
  379. (goto-char (point-min))
  380. (xml-parse-tag-1 parse-dtd parse-ns)))))
  381. (defun xml-parse-tag-1 (&optional parse-dtd parse-ns)
  382. "Like `xml-parse-tag', but possibly modify the buffer while working."
  383. (let* ((xml-validating-parser (or parse-dtd xml-validating-parser))
  384. (xml-ns
  385. (cond ((eq parse-ns 'symbol-qnames)
  386. (cons 'symbol-qnames xml-default-ns))
  387. ((or (consp (car-safe parse-ns))
  388. (and (eq (car-safe parse-ns) 'symbol-qnames)
  389. (listp (cdr parse-ns))))
  390. parse-ns)
  391. (parse-ns
  392. xml-default-ns))))
  393. (cond
  394. ;; Processing instructions, like <?xml version="1.0"?>.
  395. ((looking-at-p "<\\?")
  396. (search-forward "?>")
  397. (skip-syntax-forward " ")
  398. (xml-parse-tag-1 parse-dtd xml-ns))
  399. ;; Character data (CDATA) sections, in which no tag should be interpreted
  400. ((looking-at "<!\\[CDATA\\[")
  401. (let ((pos (match-end 0)))
  402. (unless (search-forward "]]>" nil t)
  403. (error "XML: (Not Well Formed) CDATA section does not end anywhere in the document"))
  404. (concat
  405. (buffer-substring-no-properties pos (match-beginning 0))
  406. (xml-parse-string))))
  407. ;; DTD for the document
  408. ((looking-at-p "<!DOCTYPE[ \t\n\r]")
  409. (let ((dtd (xml-parse-dtd parse-ns)))
  410. (skip-syntax-forward " ")
  411. (if xml-validating-parser
  412. (cons dtd (xml-parse-tag-1 nil xml-ns))
  413. (xml-parse-tag-1 nil xml-ns))))
  414. ;; skip comments
  415. ((looking-at-p "<!--")
  416. (search-forward "-->")
  417. ;; FIXME: This loses the skipped-over spaces.
  418. (skip-syntax-forward " ")
  419. (unless (eobp)
  420. (let ((xml-sub-parser t))
  421. (xml-parse-tag-1 parse-dtd xml-ns))))
  422. ;; end tag
  423. ((looking-at-p "</")
  424. '())
  425. ;; opening tag
  426. ((looking-at (eval-when-compile (concat "<\\(" xml-name-re "\\)")))
  427. (goto-char (match-end 1))
  428. ;; Parse this node
  429. (let* ((node-name (match-string-no-properties 1))
  430. ;; Parse the attribute list.
  431. (attrs (xml-parse-attlist xml-ns))
  432. children)
  433. ;; add the xmlns:* attrs to our cache
  434. (when (consp xml-ns)
  435. (dolist (attr attrs)
  436. (when (and (consp (car attr))
  437. (equal "http://www.w3.org/2000/xmlns/"
  438. (caar attr)))
  439. (push (cons (cdar attr) (cdr attr))
  440. (if (symbolp (car xml-ns))
  441. (cdr xml-ns)
  442. xml-ns)))))
  443. (setq children (list attrs (xml-maybe-do-ns node-name "" xml-ns)))
  444. (cond
  445. ;; is this an empty element ?
  446. ((looking-at-p "/>")
  447. (forward-char 2)
  448. (nreverse children))
  449. ;; is this a valid start tag ?
  450. ((eq (char-after) ?>)
  451. (forward-char 1)
  452. ;; Now check that we have the right end-tag.
  453. (let ((end (concat "</" node-name "\\s-*>")))
  454. (while (not (looking-at end))
  455. (cond
  456. ((eobp)
  457. (error "XML: (Not Well-Formed) End of document while reading element `%s'"
  458. node-name))
  459. ((looking-at-p "</")
  460. (forward-char 2)
  461. (error "XML: (Not Well-Formed) Invalid end tag `%s' (expecting `%s')"
  462. (let ((pos (point)))
  463. (buffer-substring pos (if (re-search-forward "\\s-*>" nil t)
  464. (match-beginning 0)
  465. (point-max))))
  466. node-name))
  467. ;; Read a sub-element and push it onto CHILDREN.
  468. ((= (char-after) ?<)
  469. (let ((tag (xml-parse-tag-1 nil xml-ns)))
  470. (when tag
  471. (push tag children))))
  472. ;; Read some character data.
  473. (t
  474. (let ((expansion (xml-parse-string)))
  475. (push (if (stringp (car children))
  476. ;; If two strings were separated by a
  477. ;; comment, concat them.
  478. (concat (pop children) expansion)
  479. expansion)
  480. children)))))
  481. ;; Move point past the end-tag.
  482. (goto-char (match-end 0))
  483. (nreverse children)))
  484. ;; Otherwise this was an invalid start tag (expected ">" not found.)
  485. (t
  486. (error "XML: (Well-Formed) Couldn't parse tag: %s"
  487. (buffer-substring-no-properties (- (point) 10) (+ (point) 1)))))))
  488. ;; (Not one of PI, CDATA, Comment, End tag, or Start tag)
  489. (t
  490. (unless xml-sub-parser ; Usually, we error out.
  491. (error "XML: (Well-Formed) Invalid character"))
  492. ;; However, if we're parsing incrementally, then we need to deal
  493. ;; with stray CDATA.
  494. (let ((s (xml-parse-string)))
  495. (when (zerop (length s))
  496. ;; We haven't consumed any input! We must throw an error in
  497. ;; order to prevent looping forever.
  498. (error "XML: (Not Well-Formed) Could not parse: %s"
  499. (buffer-substring-no-properties
  500. (point) (min (+ (point) 10) (point-max)))))
  501. s)))))
  502. (defun xml-parse-string ()
  503. "Parse character data at point, and return it as a string.
  504. Leave point at the start of the next thing to parse. This
  505. function can modify the buffer by expanding entity and character
  506. references."
  507. (let ((start (point))
  508. ;; Keep track of the size of the rest of the buffer:
  509. (old-remaining-size (- (buffer-size) (point)))
  510. ref val)
  511. (while (and (not (eobp))
  512. (not (looking-at-p "<")))
  513. ;; Find the next < or & character.
  514. (skip-chars-forward "^<&")
  515. (when (eq (char-after) ?&)
  516. ;; If we find an entity or character reference, expand it.
  517. (unless (looking-at xml-entity-or-char-ref-re)
  518. (error "XML: (Not Well-Formed) Invalid entity reference"))
  519. ;; For a character reference, the next entity or character
  520. ;; reference must be after the replacement. [4.6] "Numerical
  521. ;; character references are expanded immediately when
  522. ;; recognized and MUST be treated as character data."
  523. (if (setq ref (match-string 2))
  524. (progn ; Numeric char reference
  525. (setq val (save-match-data
  526. (decode-char 'ucs (string-to-number
  527. ref (if (match-string 1) 16)))))
  528. (and (null val)
  529. xml-validating-parser
  530. (error "XML: (Validity) Invalid character reference `%s'"
  531. (match-string 0)))
  532. (replace-match (if val (string val) xml-undefined-entity) t t))
  533. ;; For an entity reference, search again from the start of
  534. ;; the replaced text, since the replacement can contain
  535. ;; entity or character references, or markup.
  536. (setq ref (match-string 3)
  537. val (assoc ref xml-entity-alist))
  538. (and (null val)
  539. xml-validating-parser
  540. (error "XML: (Validity) Undefined entity `%s'" ref))
  541. (replace-match (or (cdr val) xml-undefined-entity) t t)
  542. (goto-char (match-beginning 0)))
  543. ;; Check for XML bombs.
  544. (and xml-entity-expansion-limit
  545. (> (- (buffer-size) (point))
  546. (+ old-remaining-size xml-entity-expansion-limit))
  547. (error "XML: Entity reference expansion \
  548. surpassed `xml-entity-expansion-limit'"))))
  549. ;; [2.11] Clean up line breaks.
  550. (let ((end-marker (point-marker)))
  551. (goto-char start)
  552. (while (re-search-forward "\r\n?" end-marker t)
  553. (replace-match "\n" t t))
  554. (goto-char end-marker)
  555. (buffer-substring start (point)))))
  556. (defun xml-parse-attlist (&optional xml-ns)
  557. "Return the attribute-list after point.
  558. Leave point at the first non-blank character after the tag."
  559. (let ((attlist ())
  560. end-pos name)
  561. (skip-syntax-forward " ")
  562. (while (looking-at (eval-when-compile
  563. (concat "\\(" xml-name-re "\\)\\s-*=\\s-*")))
  564. (setq end-pos (match-end 0))
  565. (setq name (xml-maybe-do-ns (match-string-no-properties 1) nil xml-ns))
  566. (goto-char end-pos)
  567. ;; See also: http://www.w3.org/TR/2000/REC-xml-20001006#AVNormalize
  568. ;; Do we have a string between quotes (or double-quotes),
  569. ;; or a simple word ?
  570. (if (looking-at "\"\\([^\"]*\\)\"")
  571. (setq end-pos (match-end 0))
  572. (if (looking-at "'\\([^']*\\)'")
  573. (setq end-pos (match-end 0))
  574. (error "XML: (Not Well-Formed) Attribute values must be given between quotes")))
  575. ;; Each attribute must be unique within a given element
  576. (if (assoc name attlist)
  577. (error "XML: (Not Well-Formed) Each attribute must be unique within an element"))
  578. ;; Multiple whitespace characters should be replaced with a single one
  579. ;; in the attributes
  580. (let ((string (match-string-no-properties 1)))
  581. (replace-regexp-in-string "\\s-\\{2,\\}" " " string)
  582. (let ((expansion (xml-substitute-special string)))
  583. (unless (stringp expansion)
  584. ;; We say this is the constraint. It is actually that
  585. ;; neither external entities nor "<" can be in an
  586. ;; attribute value.
  587. (error "XML: (Not Well-Formed) Entities in attributes cannot expand into elements"))
  588. (push (cons name expansion) attlist)))
  589. (goto-char end-pos)
  590. (skip-syntax-forward " "))
  591. (nreverse attlist)))
  592. ;;; DTD (document type declaration)
  593. ;; The following functions know how to skip or parse the DTD of a
  594. ;; document. FIXME: it fails at least if the DTD contains conditional
  595. ;; sections.
  596. (defun xml-skip-dtd ()
  597. "Skip the DTD at point.
  598. This follows the rule [28] in the XML specifications."
  599. (let ((xml-validating-parser nil))
  600. (xml-parse-dtd)))
  601. (defun xml-parse-dtd (&optional _parse-ns)
  602. "Parse the DTD at point."
  603. (forward-char (eval-when-compile (length "<!DOCTYPE")))
  604. (skip-syntax-forward " ")
  605. (if (and (looking-at-p ">")
  606. xml-validating-parser)
  607. (error "XML: (Validity) Invalid DTD (expecting name of the document)"))
  608. ;; Get the name of the document
  609. (looking-at xml-name-re)
  610. (let ((dtd (list (match-string-no-properties 0) 'dtd))
  611. (xml-parameter-entity-alist xml-parameter-entity-alist)
  612. next-parameter-entity)
  613. (goto-char (match-end 0))
  614. (skip-syntax-forward " ")
  615. ;; External subset (XML [75])
  616. (cond ((looking-at "PUBLIC\\s-+")
  617. (goto-char (match-end 0))
  618. (unless (or (re-search-forward
  619. "\\=\"\\([[:space:][:alnum:]-'()+,./:=?;!*#@$_%]*\\)\""
  620. nil t)
  621. (re-search-forward
  622. "\\='\\([[:space:][:alnum:]-()+,./:=?;!*#@$_%]*\\)'"
  623. nil t))
  624. (error "XML: Missing Public ID"))
  625. (let ((pubid (match-string-no-properties 1)))
  626. (skip-syntax-forward " ")
  627. (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
  628. (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
  629. (error "XML: Missing System ID"))
  630. (push (list pubid (match-string-no-properties 1) 'public) dtd)))
  631. ((looking-at "SYSTEM\\s-+")
  632. (goto-char (match-end 0))
  633. (unless (or (re-search-forward "\\='\\([^']*\\)'" nil t)
  634. (re-search-forward "\\=\"\\([^\"]*\\)\"" nil t))
  635. (error "XML: Missing System ID"))
  636. (push (list (match-string-no-properties 1) 'system) dtd)))
  637. (skip-syntax-forward " ")
  638. (if (eq (char-after) ?>)
  639. ;; No internal subset
  640. (forward-char)
  641. ;; Internal subset (XML [28b])
  642. (unless (eq (char-after) ?\[)
  643. (error "XML: Bad DTD"))
  644. (forward-char)
  645. ;; [2.8]: "markup declarations may be made up in whole or in
  646. ;; part of the replacement text of parameter entities."
  647. ;; Since parameter entities are valid only within the DTD, we
  648. ;; first search for the position of the next possible parameter
  649. ;; entity. Then, search for the next DTD element; if it ends
  650. ;; before the next parameter entity, expand the parameter entity
  651. ;; and try again.
  652. (setq next-parameter-entity
  653. (save-excursion
  654. (if (re-search-forward xml-pe-reference-re nil t)
  655. (match-beginning 0))))
  656. ;; Parse the rest of the DTD
  657. ;; Fixme: Deal with NOTATION, PIs.
  658. (while (not (looking-at-p "\\s-*\\]"))
  659. (skip-syntax-forward " ")
  660. (cond
  661. ((eobp)
  662. (error "XML: (Well-Formed) End of document while reading DTD"))
  663. ;; Element declaration [45]:
  664. ((and (looking-at (eval-when-compile
  665. (concat "<!ELEMENT\\s-+\\(" xml-name-re
  666. "\\)\\s-+\\([^>]+\\)>")))
  667. (or (null next-parameter-entity)
  668. (<= (match-end 0) next-parameter-entity)))
  669. (let ((element (match-string-no-properties 1))
  670. (type (match-string-no-properties 2))
  671. (end-pos (match-end 0)))
  672. ;; Translation of rule [46] of XML specifications
  673. (cond
  674. ((string-match-p "\\`EMPTY\\s-*\\'" type) ; empty declaration
  675. (setq type 'empty))
  676. ((string-match-p "\\`ANY\\s-*$" type) ; any type of contents
  677. (setq type 'any))
  678. ((string-match "\\`(\\(.*\\))\\s-*\\'" type) ; children ([47])
  679. (setq type (xml-parse-elem-type
  680. (match-string-no-properties 1 type))))
  681. ((string-match-p "^%[^;]+;[ \t\n\r]*\\'" type) ; substitution
  682. nil)
  683. (xml-validating-parser
  684. (error "XML: (Validity) Invalid element type in the DTD")))
  685. ;; rule [45]: the element declaration must be unique
  686. (and (assoc element dtd)
  687. xml-validating-parser
  688. (error "XML: (Validity) DTD element declarations must be unique (<%s>)"
  689. element))
  690. ;; Store the element in the DTD
  691. (push (list element type) dtd)
  692. (goto-char end-pos)))
  693. ;; Attribute-list declaration [52] (currently unsupported):
  694. ((and (looking-at (eval-when-compile
  695. (concat "<!ATTLIST[ \t\n\r]*\\(" xml-name-re
  696. "\\)[ \t\n\r]*\\(" xml-att-def-re
  697. "\\)*[ \t\n\r]*>")))
  698. (or (null next-parameter-entity)
  699. (<= (match-end 0) next-parameter-entity)))
  700. (goto-char (match-end 0)))
  701. ;; Comments (skip to end, ignoring parameter entity):
  702. ((looking-at-p "<!--")
  703. (search-forward "-->")
  704. (and next-parameter-entity
  705. (> (point) next-parameter-entity)
  706. (setq next-parameter-entity
  707. (save-excursion
  708. (if (re-search-forward xml-pe-reference-re nil t)
  709. (match-beginning 0))))))
  710. ;; Internal entity declarations:
  711. ((and (looking-at (eval-when-compile
  712. (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
  713. xml-name-re "\\)[ \t\n\r]*\\("
  714. xml-entity-value-re "\\)[ \t\n\r]*>")))
  715. (or (null next-parameter-entity)
  716. (<= (match-end 0) next-parameter-entity)))
  717. (let* ((name (prog1 (match-string-no-properties 2)
  718. (goto-char (match-end 0))))
  719. (alist (if (match-string 1)
  720. 'xml-parameter-entity-alist
  721. 'xml-entity-alist))
  722. ;; Retrieve the deplacement text:
  723. (value (xml--entity-replacement-text
  724. ;; Entity value, sans quotation marks:
  725. (substring (match-string-no-properties 3) 1 -1))))
  726. ;; If the same entity is declared more than once, the
  727. ;; first declaration is binding.
  728. (unless (assoc name (symbol-value alist))
  729. (set alist (cons (cons name value) (symbol-value alist))))))
  730. ;; External entity declarations (currently unsupported):
  731. ((and (or (looking-at (eval-when-compile
  732. (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
  733. xml-name-re "\\)[ \t\n\r]+SYSTEM[ \t\n\r]+"
  734. "\\(\"[^\"]*\"\\|'[^']*'\\)[ \t\n\r]*>")))
  735. (looking-at (eval-when-compile
  736. (concat "<!ENTITY[ \t\n\r]+\\(%[ \t\n\r]+\\)?\\("
  737. xml-name-re "\\)[ \t\n\r]+PUBLIC[ \t\n\r]+"
  738. "\"[- \r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*\""
  739. "\\|'[- \r\na-zA-Z0-9()+,./:=?;!*#@$_%]*'"
  740. "[ \t\n\r]+\\(\"[^\"]*\"\\|'[^']*'\\)"
  741. "[ \t\n\r]*>"))))
  742. (or (null next-parameter-entity)
  743. (<= (match-end 0) next-parameter-entity)))
  744. (goto-char (match-end 0)))
  745. ;; If a parameter entity is in the way, expand it.
  746. (next-parameter-entity
  747. (save-excursion
  748. (goto-char next-parameter-entity)
  749. (unless (looking-at xml-pe-reference-re)
  750. (error "XML: Internal error"))
  751. (let* ((entity (match-string 1))
  752. (elt (assoc entity xml-parameter-entity-alist)))
  753. (if elt
  754. (progn
  755. (replace-match (cdr elt) t t)
  756. ;; The replacement can itself be a parameter entity.
  757. (goto-char next-parameter-entity))
  758. (goto-char (match-end 0))))
  759. (setq next-parameter-entity
  760. (if (re-search-forward xml-pe-reference-re nil t)
  761. (match-beginning 0)))))
  762. ;; Anything else is garbage (ignored if not validating).
  763. (xml-validating-parser
  764. (error "XML: (Validity) Invalid DTD item"))
  765. (t
  766. (skip-chars-forward "^]"))))
  767. (if (looking-at "\\s-*]>")
  768. (goto-char (match-end 0))))
  769. (nreverse dtd)))
  770. (defun xml--entity-replacement-text (string)
  771. "Return the replacement text for the entity value STRING.
  772. The replacement text is obtained by replacing character
  773. references and parameter-entity references."
  774. (let ((ref-re (eval-when-compile
  775. (concat "\\(?:&#\\([0-9]+\\)\\|&#x\\([0-9a-fA-F]+\\)\\|%\\("
  776. xml-name-re "\\)\\);")))
  777. children)
  778. (while (string-match ref-re string)
  779. (push (substring string 0 (match-beginning 0)) children)
  780. (let ((remainder (substring string (match-end 0)))
  781. ref val)
  782. (cond ((setq ref (match-string 1 string))
  783. ;; Decimal character reference
  784. (setq val (decode-char 'ucs (string-to-number ref)))
  785. (if val (push (string val) children)))
  786. ;; Hexadecimal character reference
  787. ((setq ref (match-string 2 string))
  788. (setq val (decode-char 'ucs (string-to-number ref 16)))
  789. (if val (push (string val) children)))
  790. ;; Parameter entity reference
  791. ((setq ref (match-string 3 string))
  792. (setq val (assoc ref xml-parameter-entity-alist))
  793. (and (null val)
  794. xml-validating-parser
  795. (error "XML: (Validity) Undefined parameter entity `%s'" ref))
  796. (push (or (cdr val) xml-undefined-entity) children)))
  797. (setq string remainder)))
  798. (mapconcat 'identity (nreverse (cons string children)) "")))
  799. (defun xml-parse-elem-type (string)
  800. "Convert element type STRING into a Lisp structure."
  801. (let (elem modifier)
  802. (if (string-match "(\\([^)]+\\))\\([+*?]?\\)" string)
  803. (progn
  804. (setq elem (match-string-no-properties 1 string)
  805. modifier (match-string-no-properties 2 string))
  806. (if (string-match-p "|" elem)
  807. (setq elem (cons 'choice
  808. (mapcar 'xml-parse-elem-type
  809. (split-string elem "|"))))
  810. (if (string-match-p "," elem)
  811. (setq elem (cons 'seq
  812. (mapcar 'xml-parse-elem-type
  813. (split-string elem ",")))))))
  814. (if (string-match "[ \t\n\r]*\\([^+*?]+\\)\\([+*?]?\\)" string)
  815. (setq elem (match-string-no-properties 1 string)
  816. modifier (match-string-no-properties 2 string))))
  817. (if (and (stringp elem) (string= elem "#PCDATA"))
  818. (setq elem 'pcdata))
  819. (cond
  820. ((string= modifier "+")
  821. (list '+ elem))
  822. ((string= modifier "*")
  823. (list '* elem))
  824. ((string= modifier "?")
  825. (list '\? elem))
  826. (t
  827. elem))))
  828. ;;; Substituting special XML sequences
  829. (defun xml-substitute-special (string)
  830. "Return STRING, after substituting entity and character references.
  831. STRING is assumed to occur in an XML attribute value."
  832. (let ((strlen (length string))
  833. children)
  834. (while (string-match xml-entity-or-char-ref-re string)
  835. (push (substring string 0 (match-beginning 0)) children)
  836. (let* ((remainder (substring string (match-end 0)))
  837. (is-hex (match-string 1 string)) ; Is it a hex numeric reference?
  838. (ref (match-string 2 string))) ; Numeric part of reference
  839. (if ref
  840. ;; [4.6] Character references are included as
  841. ;; character data.
  842. (let ((val (decode-char 'ucs (string-to-number ref (if is-hex 16)))))
  843. (push (cond (val (string val))
  844. (xml-validating-parser
  845. (error "XML: (Validity) Undefined character `x%s'" ref))
  846. (t xml-undefined-entity))
  847. children)
  848. (setq string remainder
  849. strlen (length string)))
  850. ;; [4.4.5] Entity references are "included in literal".
  851. ;; Note that we don't need do anything special to treat
  852. ;; quotes as normal data characters.
  853. (setq ref (match-string 3 string)) ; entity name
  854. (let ((val (or (cdr (assoc ref xml-entity-alist))
  855. (if xml-validating-parser
  856. (error "XML: (Validity) Undefined entity `%s'" ref)
  857. xml-undefined-entity))))
  858. (setq string (concat val remainder)))
  859. (and xml-entity-expansion-limit
  860. (> (length string) (+ strlen xml-entity-expansion-limit))
  861. (error "XML: Passed `xml-entity-expansion-limit' while expanding `&%s;'"
  862. ref)))))
  863. (mapconcat 'identity (nreverse (cons string children)) "")))
  864. (defun xml-substitute-numeric-entities (string)
  865. "Substitute SGML numeric entities by their respective utf characters.
  866. This function replaces numeric entities in the input STRING and
  867. returns the modified string. For example \"&#42;\" gets replaced
  868. by \"*\"."
  869. (if (and string (stringp string))
  870. (let ((start 0))
  871. (while (string-match "&#\\([0-9]+\\);" string start)
  872. (ignore-errors
  873. (setq string (replace-match
  874. (string (read (substring string
  875. (match-beginning 1)
  876. (match-end 1))))
  877. nil nil string)))
  878. (setq start (1+ (match-beginning 0))))
  879. string)
  880. nil))
  881. ;;; Printing a parse tree (mainly for debugging).
  882. (defun xml-debug-print (xml &optional indent-string)
  883. "Outputs the XML in the current buffer.
  884. XML can be a tree or a list of nodes.
  885. The first line is indented with the optional INDENT-STRING."
  886. (setq indent-string (or indent-string ""))
  887. (dolist (node xml)
  888. (xml-debug-print-internal node indent-string)))
  889. (defalias 'xml-print 'xml-debug-print)
  890. (defun xml-escape-string (string)
  891. "Convert STRING into a string containing valid XML character data.
  892. Replace occurrences of &<>\\='\" in STRING with their default XML
  893. entity references (e.g., replace each & with &amp;).
  894. XML character data must not contain & or < characters, nor the >
  895. character under some circumstances. The XML spec does not impose
  896. restriction on \" or \\=', but we just substitute for these too
  897. \(as is permitted by the spec)."
  898. (with-temp-buffer
  899. (insert string)
  900. (dolist (substitution '(("&" . "&amp;")
  901. ("<" . "&lt;")
  902. (">" . "&gt;")
  903. ("'" . "&apos;")
  904. ("\"" . "&quot;")))
  905. (goto-char (point-min))
  906. (while (search-forward (car substitution) nil t)
  907. (replace-match (cdr substitution) t t nil)))
  908. (buffer-string)))
  909. (defun xml-debug-print-internal (xml indent-string)
  910. "Outputs the XML tree in the current buffer.
  911. The first line is indented with INDENT-STRING."
  912. (let ((tree xml)
  913. attlist)
  914. (insert indent-string ?< (symbol-name (xml-node-name tree)))
  915. ;; output the attribute list
  916. (setq attlist (xml-node-attributes tree))
  917. (while attlist
  918. (insert ?\ (symbol-name (caar attlist)) "=\""
  919. (xml-escape-string (cdar attlist)) ?\")
  920. (setq attlist (cdr attlist)))
  921. (setq tree (xml-node-children tree))
  922. (if (null tree)
  923. (insert ?/ ?>)
  924. (insert ?>)
  925. ;; output the children
  926. (dolist (node tree)
  927. (cond
  928. ((listp node)
  929. (insert ?\n)
  930. (xml-debug-print-internal node (concat indent-string " ")))
  931. ((stringp node)
  932. (insert (xml-escape-string node)))
  933. (t
  934. (error "Invalid XML tree"))))
  935. (when (not (and (null (cdr tree))
  936. (stringp (car tree))))
  937. (insert ?\n indent-string))
  938. (insert ?< ?/ (symbol-name (xml-node-name xml)) ?>))))
  939. (provide 'xml)
  940. ;;; xml.el ends here