]> git.saurik.com Git - wxWidgets.git/blame - src/xml/xml.cpp
Use without mimetypes enabled
[wxWidgets.git] / src / xml / xml.cpp
CommitLineData
27b0c286
VS
1/////////////////////////////////////////////////////////////////////////////
2// Name: xml.cpp
3// Purpose: wxXmlDocument - XML parser & data holder class
4// Author: Vaclav Slavik
5// Created: 2000/03/05
6// RCS-ID: $Id$
7// Copyright: (c) 2000 Vaclav Slavik
65571936 8// Licence: wxWindows licence
27b0c286
VS
9/////////////////////////////////////////////////////////////////////////////
10
14f355c2 11#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
27b0c286
VS
12#pragma implementation "xml.h"
13#endif
14
15// For compilers that support precompilation, includes "wx.h".
16#include "wx/wxprec.h"
17
18#ifdef __BORLANDC__
19 #pragma hdrstop
20#endif
21
22#include "wx/xml/xml.h"
23
24#if wxUSE_XML
25
26#include "wx/wfstream.h"
27#include "wx/datstrm.h"
28#include "wx/zstream.h"
29#include "wx/log.h"
30#include "wx/intl.h"
31#include "wx/strconv.h"
32
33#include "expat.h" // from Expat
34
34fdf762
VS
35// DLL options compatibility check:
36#include "wx/app.h"
37WX_CHECK_BUILD_OPTIONS("wxXML")
38
27b0c286
VS
39//-----------------------------------------------------------------------------
40// wxXmlNode
41//-----------------------------------------------------------------------------
42
43wxXmlNode::wxXmlNode(wxXmlNode *parent,wxXmlNodeType type,
44 const wxString& name, const wxString& content,
45 wxXmlProperty *props, wxXmlNode *next)
46 : m_type(type), m_name(name), m_content(content),
47 m_properties(props), m_parent(parent),
48 m_children(NULL), m_next(next)
49{
50 if (m_parent)
51 {
52 if (m_parent->m_children)
53 {
54 m_next = m_parent->m_children;
55 m_parent->m_children = this;
56 }
57 else
58 m_parent->m_children = this;
59 }
60}
61
62wxXmlNode::wxXmlNode(wxXmlNodeType type, const wxString& name,
63 const wxString& content)
64 : m_type(type), m_name(name), m_content(content),
65 m_properties(NULL), m_parent(NULL),
66 m_children(NULL), m_next(NULL)
67{}
68
69wxXmlNode::wxXmlNode(const wxXmlNode& node)
70{
71 m_next = NULL;
72 m_parent = NULL;
73 DoCopy(node);
74}
75
76wxXmlNode::~wxXmlNode()
77{
78 wxXmlNode *c, *c2;
79 for (c = m_children; c; c = c2)
80 {
81 c2 = c->m_next;
82 delete c;
83 }
84
85 wxXmlProperty *p, *p2;
86 for (p = m_properties; p; p = p2)
87 {
88 p2 = p->GetNext();
89 delete p;
90 }
91}
92
93wxXmlNode& wxXmlNode::operator=(const wxXmlNode& node)
94{
95 wxDELETE(m_properties);
96 wxDELETE(m_children);
97 DoCopy(node);
98 return *this;
99}
100
101void wxXmlNode::DoCopy(const wxXmlNode& node)
102{
103 m_type = node.m_type;
104 m_name = node.m_name;
105 m_content = node.m_content;
106 m_children = NULL;
107
108 wxXmlNode *n = node.m_children;
109 while (n)
110 {
111 AddChild(new wxXmlNode(*n));
112 n = n->GetNext();
113 }
114
115 m_properties = NULL;
116 wxXmlProperty *p = node.m_properties;
117 while (p)
118 {
119 AddProperty(p->GetName(), p->GetValue());
120 p = p->GetNext();
121 }
122}
123
124bool wxXmlNode::HasProp(const wxString& propName) const
125{
126 wxXmlProperty *prop = GetProperties();
127
128 while (prop)
129 {
130 if (prop->GetName() == propName) return TRUE;
131 prop = prop->GetNext();
132 }
133
134 return FALSE;
135}
136
137bool wxXmlNode::GetPropVal(const wxString& propName, wxString *value) const
138{
139 wxXmlProperty *prop = GetProperties();
140
141 while (prop)
142 {
143 if (prop->GetName() == propName)
144 {
145 *value = prop->GetValue();
146 return TRUE;
147 }
148 prop = prop->GetNext();
149 }
150
151 return FALSE;
152}
153
154wxString wxXmlNode::GetPropVal(const wxString& propName, const wxString& defaultVal) const
155{
156 wxString tmp;
157 if (GetPropVal(propName, &tmp))
158 return tmp;
0e2710a6
DS
159
160 return defaultVal;
27b0c286
VS
161}
162
163void wxXmlNode::AddChild(wxXmlNode *child)
164{
165 if (m_children == NULL)
166 m_children = child;
167 else
168 {
169 wxXmlNode *ch = m_children;
170 while (ch->m_next) ch = ch->m_next;
171 ch->m_next = child;
172 }
173 child->m_next = NULL;
174 child->m_parent = this;
175}
176
177void wxXmlNode::InsertChild(wxXmlNode *child, wxXmlNode *before_node)
178{
179 wxASSERT_MSG(before_node->GetParent() == this, wxT("wxXmlNode::InsertChild - the node has incorrect parent"));
180
181 if (m_children == before_node)
182 m_children = child;
183 else
184 {
185 wxXmlNode *ch = m_children;
186 while (ch->m_next != before_node) ch = ch->m_next;
187 ch->m_next = child;
188 }
189
190 child->m_parent = this;
191 child->m_next = before_node;
192}
193
194bool wxXmlNode::RemoveChild(wxXmlNode *child)
195{
196 if (m_children == NULL)
197 return FALSE;
198 else if (m_children == child)
199 {
200 m_children = child->m_next;
201 child->m_parent = NULL;
202 child->m_next = NULL;
203 return TRUE;
204 }
205 else
206 {
207 wxXmlNode *ch = m_children;
208 while (ch->m_next)
209 {
210 if (ch->m_next == child)
211 {
212 ch->m_next = child->m_next;
213 child->m_parent = NULL;
214 child->m_next = NULL;
215 return TRUE;
216 }
217 ch = ch->m_next;
218 }
219 return FALSE;
220 }
221}
222
223void wxXmlNode::AddProperty(const wxString& name, const wxString& value)
224{
225 AddProperty(new wxXmlProperty(name, value, NULL));
226}
227
228void wxXmlNode::AddProperty(wxXmlProperty *prop)
229{
230 if (m_properties == NULL)
231 m_properties = prop;
232 else
233 {
234 wxXmlProperty *p = m_properties;
235 while (p->GetNext()) p = p->GetNext();
236 p->SetNext(prop);
237 }
238}
239
240bool wxXmlNode::DeleteProperty(const wxString& name)
241{
242 wxXmlProperty *prop;
243
244 if (m_properties == NULL)
245 return FALSE;
246
247 else if (m_properties->GetName() == name)
248 {
249 prop = m_properties;
250 m_properties = prop->GetNext();
251 prop->SetNext(NULL);
252 delete prop;
253 return TRUE;
254 }
255
256 else
257 {
258 wxXmlProperty *p = m_properties;
259 while (p->GetNext())
260 {
261 if (p->GetNext()->GetName() == name)
262 {
263 prop = p->GetNext();
264 p->SetNext(prop->GetNext());
265 prop->SetNext(NULL);
266 delete prop;
267 return TRUE;
268 }
269 p = p->GetNext();
270 }
271 return FALSE;
272 }
273}
274
275
276
277//-----------------------------------------------------------------------------
278// wxXmlDocument
279//-----------------------------------------------------------------------------
280
281wxXmlDocument::wxXmlDocument()
282 : m_version(wxT("1.0")), m_fileEncoding(wxT("utf-8")), m_root(NULL)
283{
284#if !wxUSE_UNICODE
285 m_encoding = wxT("UTF-8");
286#endif
287}
288
289wxXmlDocument::wxXmlDocument(const wxString& filename, const wxString& encoding)
d0468e8c 290 :wxObject(), m_root(NULL)
27b0c286
VS
291{
292 if ( !Load(filename, encoding) )
293 {
294 wxDELETE(m_root);
295 }
296}
297
298wxXmlDocument::wxXmlDocument(wxInputStream& stream, const wxString& encoding)
d0468e8c 299 :wxObject(), m_root(NULL)
27b0c286
VS
300{
301 if ( !Load(stream, encoding) )
302 {
303 wxDELETE(m_root);
304 }
305}
306
307wxXmlDocument::wxXmlDocument(const wxXmlDocument& doc)
d0468e8c 308 :wxObject()
27b0c286
VS
309{
310 DoCopy(doc);
311}
312
313wxXmlDocument& wxXmlDocument::operator=(const wxXmlDocument& doc)
314{
315 wxDELETE(m_root);
316 DoCopy(doc);
317 return *this;
318}
319
320void wxXmlDocument::DoCopy(const wxXmlDocument& doc)
321{
322 m_version = doc.m_version;
323#if !wxUSE_UNICODE
324 m_encoding = doc.m_encoding;
325#endif
326 m_fileEncoding = doc.m_fileEncoding;
327 m_root = new wxXmlNode(*doc.m_root);
328}
329
330bool wxXmlDocument::Load(const wxString& filename, const wxString& encoding)
331{
332 wxFileInputStream stream(filename);
333 return Load(stream, encoding);
334}
335
336bool wxXmlDocument::Save(const wxString& filename) const
337{
338 wxFileOutputStream stream(filename);
339 return Save(stream);
340}
341
342
343
344//-----------------------------------------------------------------------------
345// wxXmlDocument loading routines
346//-----------------------------------------------------------------------------
347
348/*
349 FIXME:
350 - process all elements, including CDATA
351 */
352
353// converts Expat-produced string in UTF-8 into wxString.
354inline static wxString CharToString(wxMBConv *conv,
355 const char *s, size_t len = wxSTRING_MAXLEN)
356{
357#if wxUSE_UNICODE
358 (void)conv;
359 return wxString(s, wxConvUTF8, len);
360#else
361 if ( conv )
362 {
363 size_t nLen = (len != wxSTRING_MAXLEN) ? len :
e4f21fec 364 wxConvUTF8.MB2WC((wchar_t*) NULL, s, 0);
27b0c286
VS
365
366 wchar_t *buf = new wchar_t[nLen+1];
367 wxConvUTF8.MB2WC(buf, s, nLen);
368 buf[nLen] = 0;
369 wxString str(buf, *conv, len);
370 delete[] buf;
371 return str;
372 }
373 else
088ab984 374 return wxString(s, len != wxSTRING_MAXLEN ? len : strlen(s));
27b0c286
VS
375#endif
376}
377
378struct wxXmlParsingContext
379{
380 wxMBConv *conv;
381 wxXmlNode *root;
382 wxXmlNode *node;
383 wxXmlNode *lastAsText;
384 wxString encoding;
385 wxString version;
386};
387
388static void StartElementHnd(void *userData, const char *name, const char **atts)
389{
390 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
391 wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE, CharToString(ctx->conv, name));
392 const char **a = atts;
393 while (*a)
394 {
395 node->AddProperty(CharToString(ctx->conv, a[0]), CharToString(ctx->conv, a[1]));
396 a += 2;
397 }
398 if (ctx->root == NULL)
399 ctx->root = node;
400 else
401 ctx->node->AddChild(node);
402 ctx->node = node;
403 ctx->lastAsText = NULL;
404}
405
406static void EndElementHnd(void *userData, const char* WXUNUSED(name))
407{
408 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
409
410 ctx->node = ctx->node->GetParent();
411 ctx->lastAsText = NULL;
412}
413
414static void TextHnd(void *userData, const char *s, int len)
415{
416 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
417 char *buf = new char[len + 1];
418
419 buf[len] = '\0';
420 memcpy(buf, s, (size_t)len);
421
422 if (ctx->lastAsText)
423 {
424 ctx->lastAsText->SetContent(ctx->lastAsText->GetContent() +
425 CharToString(ctx->conv, buf));
426 }
427 else
428 {
429 bool whiteOnly = TRUE;
430 for (char *c = buf; *c != '\0'; c++)
431 if (*c != ' ' && *c != '\t' && *c != '\n' && *c != '\r')
432 {
433 whiteOnly = FALSE;
434 break;
435 }
436 if (!whiteOnly)
437 {
438 ctx->lastAsText = new wxXmlNode(wxXML_TEXT_NODE, wxT("text"),
439 CharToString(ctx->conv, buf));
440 ctx->node->AddChild(ctx->lastAsText);
441 }
442 }
443
444 delete[] buf;
445}
446
447static void CommentHnd(void *userData, const char *data)
448{
449 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
450
451 if (ctx->node)
452 {
453 // VS: ctx->node == NULL happens if there is a comment before
454 // the root element (e.g. wxDesigner's output). We ignore such
455 // comments, no big deal...
456 ctx->node->AddChild(new wxXmlNode(wxXML_COMMENT_NODE,
457 wxT("comment"), CharToString(ctx->conv, data)));
458 }
459 ctx->lastAsText = NULL;
460}
461
462static void DefaultHnd(void *userData, const char *s, int len)
463{
464 // XML header:
465 if (len > 6 && memcmp(s, "<?xml ", 6) == 0)
466 {
467 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
468
469 wxString buf = CharToString(ctx->conv, s, (size_t)len);
470 int pos;
471 pos = buf.Find(wxT("encoding="));
472 if (pos != wxNOT_FOUND)
473 ctx->encoding = buf.Mid(pos + 10).BeforeFirst(buf[(size_t)pos+9]);
474 pos = buf.Find(wxT("version="));
475 if (pos != wxNOT_FOUND)
476 ctx->version = buf.Mid(pos + 9).BeforeFirst(buf[(size_t)pos+8]);
477 }
478}
479
480static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData),
481 const XML_Char *name, XML_Encoding *info)
482{
483 // We must build conversion table for expat. The easiest way to do so
484 // is to let wxCSConv convert as string containing all characters to
485 // wide character representation:
42841dfc
WS
486 wxString str(name, wxConvLibc);
487 wxCSConv conv(str);
27b0c286
VS
488 char mbBuf[2];
489 wchar_t wcBuf[10];
490 size_t i;
491
492 mbBuf[1] = 0;
493 info->map[0] = 0;
494 for (i = 0; i < 255; i++)
495 {
496 mbBuf[0] = (char)(i+1);
497 if (conv.MB2WC(wcBuf, mbBuf, 2) == (size_t)-1)
498 {
499 // invalid/undefined byte in the encoding:
500 info->map[i+1] = -1;
501 }
502 info->map[i+1] = (int)wcBuf[0];
503 }
42841dfc 504
27b0c286
VS
505 info->data = NULL;
506 info->convert = NULL;
507 info->release = NULL;
508
509 return 1;
510}
511
512bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding)
513{
514#if wxUSE_UNICODE
515 (void)encoding;
516#else
517 m_encoding = encoding;
518#endif
519
520 const size_t BUFSIZE = 1024;
521 char buf[BUFSIZE];
522 wxXmlParsingContext ctx;
523 bool done;
524 XML_Parser parser = XML_ParserCreate(NULL);
525
526 ctx.root = ctx.node = NULL;
527 ctx.encoding = wxT("UTF-8"); // default in absence of encoding=""
528 ctx.conv = NULL;
529#if !wxUSE_UNICODE
530 if ( encoding != wxT("UTF-8") && encoding != wxT("utf-8") )
531 ctx.conv = new wxCSConv(encoding);
532#endif
533
534 XML_SetUserData(parser, (void*)&ctx);
535 XML_SetElementHandler(parser, StartElementHnd, EndElementHnd);
536 XML_SetCharacterDataHandler(parser, TextHnd);
537 XML_SetCommentHandler(parser, CommentHnd);
538 XML_SetDefaultHandler(parser, DefaultHnd);
539 XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL);
540
541 bool ok = true;
542 do
543 {
544 size_t len = stream.Read(buf, BUFSIZE).LastRead();
545 done = (len < BUFSIZE);
546 if (!XML_Parse(parser, buf, len, done))
547 {
6a8fb6bd
VS
548 wxString error(XML_ErrorString(XML_GetErrorCode(parser)),
549 *wxConvCurrent);
27b0c286 550 wxLogError(_("XML parsing error: '%s' at line %d"),
6a8fb6bd 551 error.c_str(),
27b0c286
VS
552 XML_GetCurrentLineNumber(parser));
553 ok = false;
554 break;
555 }
556 } while (!done);
557
558 if (ok)
559 {
6a8fb6bd
VS
560 if (!ctx.version.IsEmpty())
561 SetVersion(ctx.version);
562 if (!ctx.encoding.IsEmpty())
563 SetFileEncoding(ctx.encoding);
27b0c286
VS
564 SetRoot(ctx.root);
565 }
6a8fb6bd
VS
566 else
567 {
568 delete ctx.root;
569 }
27b0c286
VS
570
571 XML_ParserFree(parser);
572#if !wxUSE_UNICODE
573 if ( ctx.conv )
574 delete ctx.conv;
575#endif
576
577 return ok;
578
579}
580
581
582
583//-----------------------------------------------------------------------------
584// wxXmlDocument saving routines
585//-----------------------------------------------------------------------------
586
587// write string to output:
588inline static void OutputString(wxOutputStream& stream, const wxString& str,
0e2710a6
DS
589#if wxUSE_UNICODE
590 wxMBConv * WXUNUSED(convMem),
591#else
592 wxMBConv *convMem,
593#endif
594 wxMBConv *convFile)
27b0c286
VS
595{
596 if (str.IsEmpty()) return;
597#if wxUSE_UNICODE
6a8fb6bd 598 const wxWX2MBbuf buf(str.mb_str(*(convFile ? convFile : &wxConvUTF8)));
27b0c286
VS
599 stream.Write((const char*)buf, strlen((const char*)buf));
600#else
601 if ( convFile == NULL )
602 stream.Write(str.mb_str(), str.Len());
603 else
604 {
605 wxString str2(str.wc_str(*convMem), *convFile);
606 stream.Write(str2.mb_str(), str2.Len());
607 }
608#endif
609}
610
611// Same as above, but create entities first.
612// Translates '<' to "&lt;", '>' to "&gt;" and '&' to "&amp;"
613static void OutputStringEnt(wxOutputStream& stream, const wxString& str,
ebf0700d
VS
614 wxMBConv *convMem, wxMBConv *convFile,
615 bool escapeQuotes = false)
27b0c286
VS
616{
617 wxString buf;
618 size_t i, last, len;
619 wxChar c;
620
621 len = str.Len();
622 last = 0;
623 for (i = 0; i < len; i++)
624 {
625 c = str.GetChar(i);
626 if (c == wxT('<') || c == wxT('>') ||
ebf0700d
VS
627 (c == wxT('&') && str.Mid(i+1, 4) != wxT("amp;")) ||
628 (escapeQuotes && c == wxT('"')))
27b0c286
VS
629 {
630 OutputString(stream, str.Mid(last, i - last), convMem, convFile);
631 switch (c)
632 {
633 case wxT('<'):
634 OutputString(stream, wxT("&lt;"), NULL, NULL);
635 break;
636 case wxT('>'):
637 OutputString(stream, wxT("&gt;"), NULL, NULL);
638 break;
639 case wxT('&'):
640 OutputString(stream, wxT("&amp;"), NULL, NULL);
641 break;
ebf0700d
VS
642 case wxT('"'):
643 OutputString(stream, wxT("&quot;"), NULL, NULL);
644 break;
27b0c286
VS
645 default: break;
646 }
647 last = i + 1;
648 }
649 }
650 OutputString(stream, str.Mid(last, i - last), convMem, convFile);
651}
652
653inline static void OutputIndentation(wxOutputStream& stream, int indent)
654{
655 wxString str = wxT("\n");
656 for (int i = 0; i < indent; i++)
657 str << wxT(' ') << wxT(' ');
658 OutputString(stream, str, NULL, NULL);
659}
660
661static void OutputNode(wxOutputStream& stream, wxXmlNode *node, int indent,
662 wxMBConv *convMem, wxMBConv *convFile)
663{
664 wxXmlNode *n, *prev;
665 wxXmlProperty *prop;
666
667 switch (node->GetType())
668 {
669 case wxXML_TEXT_NODE:
670 OutputStringEnt(stream, node->GetContent(), convMem, convFile);
671 break;
672
673 case wxXML_ELEMENT_NODE:
674 OutputString(stream, wxT("<"), NULL, NULL);
675 OutputString(stream, node->GetName(), NULL, NULL);
676
677 prop = node->GetProperties();
678 while (prop)
679 {
ebf0700d 680 OutputString(stream, wxT(" ") + prop->GetName() + wxT("=\""),
27b0c286 681 NULL, NULL);
ebf0700d
VS
682 OutputStringEnt(stream, prop->GetValue(), NULL, NULL,
683 true/*escapeQuotes*/);
684 OutputString(stream, wxT("\""), NULL, NULL);
27b0c286
VS
685 prop = prop->GetNext();
686 }
687
688 if (node->GetChildren())
689 {
690 OutputString(stream, wxT(">"), NULL, NULL);
691 prev = NULL;
692 n = node->GetChildren();
693 while (n)
694 {
695 if (n && n->GetType() != wxXML_TEXT_NODE)
696 OutputIndentation(stream, indent + 1);
697 OutputNode(stream, n, indent + 1, convMem, convFile);
698 prev = n;
699 n = n->GetNext();
700 }
701 if (prev && prev->GetType() != wxXML_TEXT_NODE)
702 OutputIndentation(stream, indent);
703 OutputString(stream, wxT("</"), NULL, NULL);
704 OutputString(stream, node->GetName(), NULL, NULL);
705 OutputString(stream, wxT(">"), NULL, NULL);
706 }
707 else
708 OutputString(stream, wxT("/>"), NULL, NULL);
709 break;
710
711 case wxXML_COMMENT_NODE:
712 OutputString(stream, wxT("<!--"), NULL, NULL);
713 OutputString(stream, node->GetContent(), convMem, convFile);
714 OutputString(stream, wxT("-->"), NULL, NULL);
715 break;
716
717 default:
718 wxFAIL_MSG(wxT("unsupported node type"));
719 }
720}
721
722bool wxXmlDocument::Save(wxOutputStream& stream) const
723{
724 if ( !IsOk() )
725 return FALSE;
726
727 wxString s;
728
729 wxMBConv *convMem = NULL, *convFile = NULL;
730#if wxUSE_UNICODE
731 convFile = new wxCSConv(GetFileEncoding());
732#else
733 if ( GetFileEncoding() != GetEncoding() )
734 {
735 convFile = new wxCSConv(GetFileEncoding());
736 convMem = new wxCSConv(GetEncoding());
737 }
738#endif
739
740 s.Printf(wxT("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
741 GetVersion().c_str(), GetFileEncoding().c_str());
742 OutputString(stream, s, NULL, NULL);
743
744 OutputNode(stream, GetRoot(), 0, convMem, convFile);
745 OutputString(stream, wxT("\n"), NULL, NULL);
746
747 if ( convFile )
748 delete convFile;
749 if ( convMem )
750 delete convMem;
751
752 return TRUE;
753}
754
755#endif // wxUSE_XML