Debian Codegraph @

examples/short_api_samples/xml_utils/mybookmarks.pas

raw
1 { Manage list of bookmarks, in particular load and save them to a simple XML file. }
2 unit MyBookmarks;
3
4 interface
5
6 uses Classes, SysUtils, Generics.Collections;
7
8 type
9 { Bookmark definition. Contains URL and additional data. }
10 TBookmark = class
11 Caption, Url: String;
12 function CaptionFinal: String;
13 end;
14
15 { List of TBookmark. }
16 TBookmarkList = class({$ifdef FPC}specialize{$endif} TObjectList<TBookmark>)
17 procedure Load;
18 procedure Save;
19 end;
20
21 const
22 BookmarksDatabase = 'my-bookmarks.xml';
23
24 implementation
25
26 uses DOM,
27 CastleXmlUtils, CastleUriUtils;
28
29 { TBookmark ------------------------------------------------------------------ }
30
31 function TBookmark.CaptionFinal: String;
32 begin
33 if Caption <> '' then
34 Result := Caption
35 else
36 Result := Url;
37 end;
38
39 { TBookmarkList -------------------------------------------------------------- }
40
41 procedure TBookmarkList.Load;
42 var
43 B: TBookmark;
44 Document: TXMLDocument;
45 I: TXMLElementIterator;
46 begin
47 Clear;
48
49 if URIFileExists(BookmarksDatabase) then
50 begin
51 Document := URLReadXML(BookmarksDatabase);
52 try
53 if Document.DocumentElement.TagName8 <> 'bookmark-list' then
54 raise Exception.CreateFmt('Bookmarks XML file has invalid top-level element: %s', [
55 Document.DocumentElement.TagName8
56 ]);
57 I := Document.DocumentElement.ChildrenIterator('bookmark');
58 try
59 while I.GetNext do
60 begin
61 B := TBookmark.Create;
62 B.Url := I.Current.AttributeString('url');
63 B.Caption := I.Current.AttributeString('caption');
64 Add(B);
65 end;
66 finally
67 FreeAndNil(I);
68 end;
69 finally
70 FreeAndNil(Document);
71 end;
72 end;
73 end;
74
75 procedure TBookmarkList.Save;
76 var
77 Document: TXMLDocument;
78 RootElement, Child: TDOMElement;
79 B: TBookmark;
80 begin
81 Document := TXMLDocument.Create;
82 try
83 RootElement := Document.CreateElement('bookmark-list');
84 Document.AppendChild(RootElement);
85
86 for B in Self do
87 begin
88 Child := RootElement.CreateChild('bookmark');
89 Child.AttributeSet('caption', B.Caption);
90 Child.AttributeSet('url', B.Url);
91 end;
92
93 URLWriteXML(Document, BookmarksDatabase);
94 finally
95 FreeAndNil(Document);
96 end;
97 end;
98
99 end.