File: xml.scrbl

package info (click to toggle)
racket 7.9%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 178,684 kB
  • sloc: ansic: 282,112; lisp: 234,887; pascal: 70,954; sh: 27,112; asm: 16,268; makefile: 4,613; cpp: 2,715; ada: 1,681; javascript: 1,244; cs: 879; exp: 499; csh: 422; python: 274; xml: 106; perl: 104
file content (581 lines) | stat: -rw-r--r-- 20,136 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#lang scribble/doc
@(require scribble/manual
          scribble/bnf
          scribble/eval
          (for-label racket/base
                     racket/contract
                     racket/list
                     xml
                     xml/plist))

@(define xml-eval (make-base-eval))
@(define plist-eval (make-base-eval))
@interaction-eval[#:eval xml-eval (require xml)]
@interaction-eval[#:eval xml-eval (require racket/list)]
@interaction-eval[#:eval plist-eval (require xml/plist)]

@title{XML: Parsing and Writing}

@author["Paul Graunke and Jay McCarthy"]

@defmodule[xml #:use-sources (xml/private/xexpr-core)]

The @racketmodname[xml] library provides functions for parsing and
generating XML. XML can be represented as an instance of the
@racket[document] structure type, or as a kind of S-expression that is
called an @deftech{X-expression}.

The @racketmodname[xml] library does not provide Document Type
Declaration (DTD) processing, including preservation of DTDs in read documents, or validation.
It also does not expand user-defined entities or read user-defined entities in attributes.
It does not interpret namespaces either.

@; ----------------------------------------------------------------------

@section{Datatypes}

@defstruct[location ([line (or/c false/c exact-nonnegative-integer?)]
                     [char (or/c false/c exact-nonnegative-integer?)]
                     [offset exact-nonnegative-integer?])]{

Represents a location in an input stream. The offset is a character offset unless @racket[xml-count-bytes] is @racket[#t], in which case it is a byte offset.}

@defthing[location/c contract?]{
 Equivalent to @racket[(or/c location? symbol? false/c)].
}

@defstruct[source ([start location/c]
                   [stop location/c])]{

Represents a source location. Other structure types extend
@racket[source].

When XML is generated from an input stream by @racket[read-xml],
locations are represented by @racket[location] instances. When XML
structures are generated by @racket[xexpr->xml], then locations are
symbols.}

@deftogether[(
@defstruct[external-dtd ([system string?])]
@defstruct[(external-dtd/public external-dtd) ([public string?])]
@defstruct[(external-dtd/system external-dtd) ()]
)]{

Represents an externally defined DTD.}

@defstruct[document-type ([name symbol?]
                          [external external-dtd?]
                          [inlined false/c])]{

Represents a document type.}

@defstruct[comment ([text string?])]{

Represents a comment.}

@defstruct[(p-i source) ([target-name symbol?]
                         [instruction string?])]{

Represents a processing instruction.}

@defthing[misc/c contract?]{
 Equivalent to @racket[(or/c comment? p-i?)]
}

@defstruct[prolog ([misc (listof misc/c)]
                   [dtd (or/c document-type false/c)]
                   [misc2 (listof misc/c)])]{
Represents a document prolog. 
}

@defstruct[document ([prolog prolog?]
                     [element element?]
                     [misc (listof misc/c)])]{
Represents a document.}

@defstruct[(element source) ([name symbol?]
                             [attributes (listof attribute?)]
                             [content (listof content/c)])]{
Represents an element.}

@defstruct[(attribute source) ([name symbol?] [value (or/c string? permissive/c)])]{

Represents an attribute within an element.}

@defthing[content/c contract?]{
 Equivalent to @racket[(or/c pcdata? element? entity? comment? cdata? p-i? permissive/c)].
}

@defthing[permissive/c contract?]{
 If @racket[(permissive-xexprs)] is @racket[#t], then equivalent to @racket[any/c], otherwise equivalent to @racket[(make-none/c 'permissive)]}

@defproc[(valid-char? [x any/c]) boolean?]{
 Returns true if @racket[x] is an exact-nonnegative-integer whose character interpretation under UTF-8 is from the set ([#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]), in accordance with section 2.2 of the XML 1.1 spec.
}

@defstruct[(entity source) ([text (or/c symbol? valid-char?)])]{

Represents a symbolic or numerical entity.}

@defstruct[(pcdata source) ([string string?])]{

Represents PCDATA content.}

@defstruct[(cdata source) ([string string?])]{

Represents CDATA content.

The @racket[string] field is assumed to be of the form
@litchar{<![CDATA[}@nonterm{content}@litchar{]]>} with proper quoting
of @nonterm{content}. Otherwise, @racket[write-xml] generates
incorrect output.}

@defstruct[(exn:invalid-xexpr exn:fail) ([code any/c])]{

Raised by @racket[validate-xexpr] when passed an invalid
@tech{X-expression}. The @racket[code] fields contains an invalid part
of the input to @racket[validate-xexpr].}

@defstruct[(exn:xml exn:fail:read) ()]{
 Raised by @racket[read-xml] when an error in the XML input is found.
}

@defproc[(xexpr? [v any/c]) boolean?]{

Returns @racket[#t] if @racket[v] is a @tech{X-expression}, @racket[#f] otherwise.

The following grammar describes expressions that create @tech{X-expressions}:

@racketgrammar[
#:literals (cons list valid-char?)
xexpr string
      (list symbol (list (list symbol string) ...) xexpr ...)
      (cons symbol (list xexpr ...))
      symbol
      valid-char?
      cdata
      misc
]

A @racket[_string] is literal data. When converted to an XML stream,
the characters of the data will be escaped as necessary.

A pair represents an element, optionally with attributes. Each
attribute's name is represented by a symbol, and its value is
represented by a string.

A @racket[_symbol] represents a symbolic entity. For example,
@racket['nbsp] represents @litchar{&nbsp;}.

An @racket[valid-char?] represents a numeric entity. For example,
@racketvalfont{#x20} represents @litchar{&#x20;}.

A @racket[_cdata] is an instance of the @racket[cdata] structure type,
and a @racket[_misc] is an instance of the @racket[comment] or
@racket[p-i] structure types.}

@defthing[xexpr/c contract?]{
 A contract that is like @racket[xexpr?] except produces a better error
 message when the value is not an @tech{X-expression}.
}

@; ----------------------------------------------------------------------

@section{X-expression Predicate and Contract}

@defmodule[xml/xexpr]

The @racketmodname[xml/xexpr] library provides just @racket[xexpr/c],
@racket[xexpr?], @racket[correct-xexpr?], and @racket[validate-xexpr]
from @racketmodname[xml] with minimal dependencies.

@; ----------------------------------------------------------------------

@section{Reading and Writing XML}

@defproc[(read-xml [in input-port? (current-input-port)]) document?]{

Reads in an XML document from the given or current input port XML
documents contain exactly one element, raising @racket[xml-read:error]
if the input stream has zero elements or more than one element.
       
Malformed xml is reported with source locations in the form
@nonterm{l}@litchar{.}@nonterm{c}@litchar{/}@nonterm{o}, where
@nonterm{l}, @nonterm{c}, and @nonterm{o} are the line number, column
number, and next port position, respectively as returned by
@racket[port-next-location].

Any non-characters other than @racket[eof] read from the input-port
appear in the document content.  Such special values may appear only
where XML content may.  See @racket[make-input-port] for information
about creating ports that return non-character values.

@examples[
#:eval xml-eval
(xml->xexpr (document-element 
             (read-xml (open-input-string 
                        "<doc><bold>hi</bold> there!</doc>"))))
]}

@defproc[(read-xml/document [in input-port? (current-input-port)]) document?]{

Like @racket[read-xml], except that the reader stops after the single element, rather than attempting to read "miscellaneous" XML content after the element. The document returned by @racket[read-xml/document] always has an empty @racket[document-misc].}

@defproc[(read-xml/element [in input-port? (current-input-port)]) element?]{

Reads a single XML element from the port.  The next non-whitespace
character read must start an XML element, but the input port can
contain other data after the element.}

@defproc[(syntax:read-xml [in input-port? (current-input-port)]
                          [#:src source-name any/c (object-name in)])
         syntax?]{

Reads in an XML document and produces a syntax object version (like
@racket[read-syntax]) of an @tech{X-expression}.}

@defproc[(syntax:read-xml/element [in input-port? (current-input-port)]
                                  [#:src source-name any/c (object-name in)])
         syntax?]{

Like @racket[syntax:real-xml], but it reads an XML element like
@racket[read-xml/element].}

@defproc[(write-xml [doc document?] [out output-port? (current-output-port)])
         void?]{

Writes a document to the given output port, currently ignoring
everything except the document's root element.}

@defproc[(write-xml/content [content content/c] [out output-port? (current-output-port)])
         void?]{

Writes document content to the given output port.}

@defproc[(display-xml [doc document?] [out output-port? (current-output-port)])
         void?]{

Like @racket[write-xml], but newlines and indentation make the output
more readable, though less technically correct when whitespace is
significant.}

@defproc[(display-xml/content [content content/c] [out output-port? (current-output-port)])
         void?]{

Like @racket[write-xml/content], but with indentation and newlines
like @racket[display-xml].}
               

@defproc[(write-xexpr [xe xexpr/c] [out output-port? (current-output-port)]
                      [#:insert-newlines? insert-newlines? any/c #f])
         void?]{

Writes an X-expression to the given output port, without using an intermediate
XML document.

If @racket[insert-newlines?] is true, the X-expression is written with newlines
before the closing angle bracket of a tag.}


@; ----------------------------------------------------------------------

@section{XML and X-expression Conversions}

@defboolparam[permissive-xexprs v]{
 If this is set to non-false, then @racket[xml->xexpr] will allow
 non-XML objects, such as other structs, in the content of the converted XML
 and leave them in place in the resulting ``@tech{X-expression}''.
}

@defproc[(xml->xexpr [content content/c]) xexpr/c]{

Converts document content into an @tech{X-expression}, using
@racket[permissive-xexprs] to determine if foreign objects are allowed.}

@defproc[(xexpr->xml [xexpr xexpr/c]) content/c]{

Converts an @tech{X-expression} into XML content.}

@defproc[(xexpr->string [xexpr xexpr/c]) string?]{

Converts an @tech{X-expression} into a string containing XML.}

@defproc[(string->xexpr [str string?]) xexpr/c]{

Converts XML represented with a string into an @tech{X-expression}.}

@defproc[(xml-attribute-encode [str string?]) string?]{

Escapes a string as required for XML attributes.

The escaping performed for attribute strings is slightly
different from that performed for body strings, in that
double-quotes must be escaped, as they would otherwise
terminate the enclosing string.

Note that this conversion is performed automatically in attribute
positions by @racket[xexpr->string], and you are therefore unlikely to
need this function unless you are using @racket[include-template] to
insert strings directly into attribute positions of HTML.

@history[#:added "6.6.0.7"]
}

@defproc[((eliminate-whitespace [tags (listof symbol?) empty]
                                [choose (boolean? . -> . boolean?) (λ (x) x)])
          [elem element?])
         element?]{

Some elements should not contain any text, only other tags, except
they often contain whitespace for formating purposes.  Given a list of
tag names as @racket[tag]s and the identity function as
@racket[choose], @racket[eliminate-whitespace] produces a function
that filters out PCDATA consisting solely of whitespace from those
elements, and it raises an error if any non-whitespace text appears.
Passing in @racket[not] as @racket[choose] filters all elements which
are not named in the @racket[tags] list.  Using @racket[(lambda (x) #t)] as
@racket[choose] filters all elements regardless of the @racket[tags]
list.}

@defproc[(validate-xexpr [v any/c]) #t]{

If @racket[v] is an @tech{X-expression}, the result is
@racket[#t]. Otherwise, @racket[exn:invalid-xexpr]s is raised, with
a message of the form ``Expected @nonterm{something}, given
@nonterm{something-else}''. The @racket[code] field of the exception
is the part of @racket[v] that caused the exception.

@examples[#:eval xml-eval
  (validate-xexpr '(doc () "over " (em () "9000") "!"))
  (validate-xexpr #\newline)
]
}

@defproc[(correct-xexpr? [v any/c]
                         [success-k (-> any/c)]
                         [fail-k (exn:invalid-xexpr? . -> . any/c)])
         any/c]{

Like @racket[validate-xexpr], except that @racket[success-k] is called
on each valid leaf, and @racket[fail-k] is called on invalid leaves;
the @racket[fail-k] may return a value instead of raising an exception
or otherwise escaping. Results from the leaves are combined with
@racket[and] to arrive at the final result.}

@; ----------------------------------------------------------------------

@section{Parameters}

@defparam[empty-tag-shorthand shorthand (or/c (one-of/c 'always 'never) (listof symbol?))]{

A parameter that determines whether output functions should use the
@litchar{<}@nonterm{tag}@litchar{/>} tag notation instead of
@litchar{<}@nonterm{tag}@litchar{>}@litchar{</}@nonterm{tag}@litchar{>}
for elements that have no content.

When the parameter is set to @racket['always], the abbreviated
notation is always used. When set of @racket['never], the abbreviated
notation is never generated.  when set to a list of symbols is
provided, tags with names in the list are abbreviated.

The abbreviated form is the preferred XML notation.  However, most
browsers designed for HTML will only properly render XHTML if the
document uses a mixture of the two formats. The
@racket[html-empty-tags] constant contains the W3 consortium's
recommended list of XHTML tags that should use the shorthand. This
list is the default value of @racket[empty-tag-shorthand].}

@defthing[html-empty-tags (listof symbol?)]{

See @racket[empty-tag-shorthand].

@examples[
#:eval xml-eval
(parameterize ([empty-tag-shorthand html-empty-tags])
  (write-xml/content (xexpr->xml `(html 
                                    (body ((bgcolor "red"))
                                      "Hi!" (br) "Bye!")))))
]}

@defboolparam[collapse-whitespace collapse?]{

A parameter that controls whether consecutive whitespace is replaced
by a single space.  CDATA sections are not affected. The default is
@racket[#f].}

@defboolparam[read-comments preserve?]{

A parameter that determines whether comments are preserved or
discarded when reading XML.  The default is @racket[#f], which
discards comments.}

@defboolparam[xml-count-bytes count-bytes?]{

A parameter that determines whether @racket[read-xml] counts
characters or bytes in its location tracking. The default is
@racket[#f], which counts characters.

You may want to use @racket[#t] if, for example, you will be
communicating these offsets to a C program that can more easily deal
with byte offsets into the character stream, as opposed to UTF-8
character offsets.}

@defboolparam[xexpr-drop-empty-attributes drop?]{

Controls whether @racket[xml->xexpr] drops or preserves attribute
sections for an element that has no attributes. The default is
@racket[#f], which means that all generated @tech{X-expression}
elements have an attributes list (even if it's empty).}

@; ----------------------------------------------------------------------

@section{PList Library}

@defmodule[xml/plist]

The @racketmodname[xml/plist] library provides the ability to read and
write XML documents that conform to the @defterm{plist} DTD, which is
used to store dictionaries of string--value associations.  This format
is used by Mac OS (both the operating system and its applications)
to store all kinds of data.

A @deftech{plist value} is a value that could be created by an
expression matching the following @racket[_pl-expr] grammar, where a
value created by a @racket[_dict-expr] is a @deftech{plist dictionary}:

@racketgrammar*[
#:literals (list quote)
[pl-expr string
          (list 'true)
          (list 'false)
          (list 'integer integer)
          (list 'real real)
          (list 'data string)
          (list 'date string)
          dict-expr
          (list 'array pl-expr ...)]
[dict-expr (list 'dict assoc-pair ...)]
[assoc-pair (list 'assoc-pair string pl-expr)]
]

@defproc[(plist-value? [any/c v]) boolean?]{

Returns @racket[#t] if @racket[v] is a @tech{plist value},
@racket[#f] otherwise.}

@defproc[(plist-dict? [any/c v]) boolean?]{

Returns @racket[#t] if @racket[v] is a @tech{plist dictionary},
@racket[#f] otherwise.}

@defproc[(read-plist [in input-port?]) plist-value?]{

Reads a plist from a port, and produces a @tech{plist value}.}

@defproc[(write-plist [dict plist-value?] [out output-port?]) void?]{

Write a @tech{plist value} to the given port.}

@examples[
#:eval plist-eval
(define my-dict
  `(dict (assoc-pair "first-key"
                     "just a string with some  whitespace")
         (assoc-pair "second-key"
                     (false))
         (assoc-pair "third-key"
                     (dict ))
         (assoc-pair "fourth-key"
                     (dict (assoc-pair "inner-key"
                                       (real 3.432))))
         (assoc-pair "fifth-key"
                     (array (integer 14)
                            "another string"
                            (true)))
         (assoc-pair "sixth-key"
                     (array))
         (assoc-pair "seventh-key"
                     (data "some data"))
         (assoc-pair "eighth-key"
                     (date "2013-05-10T20:29:55Z"))))
(define-values (in out) (make-pipe))
(write-plist my-dict out)
(close-output-port out)
(define new-dict (read-plist in))
(equal? my-dict new-dict)
]

The XML generated by @racket[write-plist] in the above example looks
like the following, if re-formatted by hand to have newlines and
indentation:

@verbatim[#:indent 2]|{
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM 
 "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
  <dict>
    <key>first-key</key>
    <string>just a string with some  whitespace</string>
    <key>second-key</key>
    <false />
    <key>third-key</key>
    <dict />
    <key>fourth-key</key>
    <dict>
      <key>inner-key</key>
      <real>3.432</real>
    </dict>
    <key>fifth-key</key>
    <array>
      <integer>14</integer>
      <string>another string</string>
      <true />
    </array>
    <key>sixth-key</key>
    <array />
    <key>seventh-key</key>
    <data>some data</data>
    <key>eighth-key</key>
    <date>2013-05-10T20:29:55Z</date>
  </dict>
</plist>
}|

@; ----------------------------------------------------------------------

@section{Simple X-expression Path Queries}

@(require (for-label xml/path))
@defmodule[xml/path]

This library provides a simple path query library for X-expressions.

@defthing[se-path? contract?]{
 A sequence of symbols followed by an optional keyword.

 The prefix of symbols specifies a path of tags from the leaves with an implicit any sequence to the root. The final, optional keyword specifies an attribute. 
}

@defproc[(se-path*/list [p se-path?] [xe xexpr?])
         (listof any/c)]{
 Returns a list of all values specified by the path @racket[p] in the X-expression @racket[xe].         
}

@defproc[(se-path* [p se-path?] [xe xexpr?])
         any/c]{
 Returns the first answer from @racket[(se-path*/list p xe)].
}

@(define path-eval (make-base-eval))
@interaction-eval[#:eval path-eval (require xml/path)]
@examples[
#:eval path-eval
       (define some-page 
         '(html (body (p ([class "awesome"]) "Hey") (p "Bar"))))
       (se-path*/list '(p) some-page)
       (se-path* '(p) some-page)
       (se-path* '(p #:class) some-page)                 
       (se-path*/list '(body) some-page)
       (se-path*/list '() some-page)
]