]> git.saurik.com Git - wxWidgets.git/blame - src/xml/xml.cpp
Add wxNumberFormatter class helping to deal with thousands separators.
[wxWidgets.git] / src / xml / xml.cpp
CommitLineData
27b0c286 1/////////////////////////////////////////////////////////////////////////////
40989e46 2// Name: src/xml/xml.cpp
27b0c286
VS
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
27b0c286
VS
11// For compilers that support precompilation, includes "wx.h".
12#include "wx/wxprec.h"
13
14#ifdef __BORLANDC__
15 #pragma hdrstop
16#endif
17
27b0c286
VS
18#if wxUSE_XML
19
40989e46
WS
20#include "wx/xml/xml.h"
21
88a7a4e1
WS
22#ifndef WX_PRECOMP
23 #include "wx/intl.h"
e4db172a 24 #include "wx/log.h"
670f9935 25 #include "wx/app.h"
88a7a4e1
WS
26#endif
27
27b0c286
VS
28#include "wx/wfstream.h"
29#include "wx/datstrm.h"
30#include "wx/zstream.h"
27b0c286 31#include "wx/strconv.h"
664e1314 32#include "wx/scopedptr.h"
ccec9093 33#include "wx/versioninfo.h"
27b0c286
VS
34
35#include "expat.h" // from Expat
36
34fdf762 37// DLL options compatibility check:
34fdf762
VS
38WX_CHECK_BUILD_OPTIONS("wxXML")
39
4c43dd90
JS
40
41IMPLEMENT_CLASS(wxXmlDocument, wxObject)
42
43
538f3830 44// a private utility used by wxXML
352d9b89 45static bool wxIsWhiteOnly(const wxString& buf);
538f3830 46
4c43dd90 47
27b0c286
VS
48//-----------------------------------------------------------------------------
49// wxXmlNode
50//-----------------------------------------------------------------------------
51
52wxXmlNode::wxXmlNode(wxXmlNode *parent,wxXmlNodeType type,
53 const wxString& name, const wxString& content,
6e26d6b7 54 wxXmlAttribute *attrs, wxXmlNode *next, int lineNo)
27b0c286 55 : m_type(type), m_name(name), m_content(content),
288b6107 56 m_attrs(attrs), m_parent(parent),
6e26d6b7 57 m_children(NULL), m_next(next),
30f6914b
JS
58 m_lineNo(lineNo),
59 m_noConversion(false)
27b0c286
VS
60{
61 if (m_parent)
62 {
63 if (m_parent->m_children)
64 {
65 m_next = m_parent->m_children;
66 m_parent->m_children = this;
67 }
68 else
69 m_parent->m_children = this;
70 }
71}
72
73wxXmlNode::wxXmlNode(wxXmlNodeType type, const wxString& name,
6e26d6b7
VS
74 const wxString& content,
75 int lineNo)
27b0c286 76 : m_type(type), m_name(name), m_content(content),
288b6107 77 m_attrs(NULL), m_parent(NULL),
6e26d6b7 78 m_children(NULL), m_next(NULL),
30f6914b 79 m_lineNo(lineNo), m_noConversion(false)
27b0c286
VS
80{}
81
82wxXmlNode::wxXmlNode(const wxXmlNode& node)
83{
84 m_next = NULL;
85 m_parent = NULL;
86 DoCopy(node);
87}
88
89wxXmlNode::~wxXmlNode()
90{
91 wxXmlNode *c, *c2;
92 for (c = m_children; c; c = c2)
93 {
94 c2 = c->m_next;
95 delete c;
96 }
97
288b6107
VS
98 wxXmlAttribute *p, *p2;
99 for (p = m_attrs; p; p = p2)
27b0c286
VS
100 {
101 p2 = p->GetNext();
102 delete p;
103 }
104}
105
106wxXmlNode& wxXmlNode::operator=(const wxXmlNode& node)
107{
288b6107 108 wxDELETE(m_attrs);
27b0c286
VS
109 wxDELETE(m_children);
110 DoCopy(node);
111 return *this;
112}
113
114void wxXmlNode::DoCopy(const wxXmlNode& node)
115{
116 m_type = node.m_type;
117 m_name = node.m_name;
118 m_content = node.m_content;
6e26d6b7 119 m_lineNo = node.m_lineNo;
30f6914b 120 m_noConversion = node.m_noConversion;
27b0c286
VS
121 m_children = NULL;
122
123 wxXmlNode *n = node.m_children;
124 while (n)
125 {
126 AddChild(new wxXmlNode(*n));
127 n = n->GetNext();
128 }
129
288b6107
VS
130 m_attrs = NULL;
131 wxXmlAttribute *p = node.m_attrs;
27b0c286
VS
132 while (p)
133 {
288b6107 134 AddAttribute(p->GetName(), p->GetValue());
27b0c286
VS
135 p = p->GetNext();
136 }
137}
138
288b6107 139bool wxXmlNode::HasAttribute(const wxString& attrName) const
27b0c286 140{
288b6107 141 wxXmlAttribute *attr = GetAttributes();
27b0c286 142
288b6107 143 while (attr)
27b0c286 144 {
288b6107
VS
145 if (attr->GetName() == attrName) return true;
146 attr = attr->GetNext();
27b0c286
VS
147 }
148
759f7272 149 return false;
27b0c286
VS
150}
151
288b6107 152bool wxXmlNode::GetAttribute(const wxString& attrName, wxString *value) const
27b0c286 153{
cc24bf91
VS
154 wxCHECK_MSG( value, false, "value argument must not be NULL" );
155
288b6107 156 wxXmlAttribute *attr = GetAttributes();
27b0c286 157
288b6107 158 while (attr)
27b0c286 159 {
288b6107 160 if (attr->GetName() == attrName)
27b0c286 161 {
288b6107 162 *value = attr->GetValue();
759f7272 163 return true;
27b0c286 164 }
288b6107 165 attr = attr->GetNext();
27b0c286
VS
166 }
167
759f7272 168 return false;
27b0c286
VS
169}
170
288b6107 171wxString wxXmlNode::GetAttribute(const wxString& attrName, const wxString& defaultVal) const
27b0c286
VS
172{
173 wxString tmp;
288b6107 174 if (GetAttribute(attrName, &tmp))
27b0c286 175 return tmp;
0e2710a6
DS
176
177 return defaultVal;
27b0c286
VS
178}
179
180void wxXmlNode::AddChild(wxXmlNode *child)
181{
182 if (m_children == NULL)
183 m_children = child;
184 else
185 {
186 wxXmlNode *ch = m_children;
187 while (ch->m_next) ch = ch->m_next;
188 ch->m_next = child;
189 }
190 child->m_next = NULL;
191 child->m_parent = this;
192}
193
5e05df3c
VS
194// inserts a new node in front of 'followingNode'
195bool wxXmlNode::InsertChild(wxXmlNode *child, wxXmlNode *followingNode)
27b0c286 196{
5e05df3c
VS
197 wxCHECK_MSG( child, false, "cannot insert a NULL node!" );
198 wxCHECK_MSG( child->m_parent == NULL, false, "node already has a parent" );
199 wxCHECK_MSG( child->m_next == NULL, false, "node already has m_next" );
200 wxCHECK_MSG( followingNode == NULL || followingNode->GetParent() == this,
201 false,
202 "wxXmlNode::InsertChild - followingNode has incorrect parent" );
203
204 // this is for backward compatibility, NULL was allowed here thanks to
205 // the confusion about followingNode's meaning
206 if ( followingNode == NULL )
207 followingNode = m_children;
208
209 if ( m_children == followingNode )
fa6a8373 210 {
fa6a8373
RR
211 child->m_next = m_children;
212 m_children = child;
fa6a8373 213 }
27b0c286
VS
214 else
215 {
216 wxXmlNode *ch = m_children;
5e05df3c
VS
217 while ( ch && ch->m_next != followingNode )
218 ch = ch->m_next;
219 if ( !ch )
220 {
221 wxFAIL_MSG( "followingNode has this node as parent, but couldn't be found among children" );
222 return false;
223 }
224
225 child->m_next = followingNode;
27b0c286
VS
226 ch->m_next = child;
227 }
228
229 child->m_parent = this;
fa6a8373 230 return true;
27b0c286
VS
231}
232
43a302f2
VS
233// inserts a new node right after 'precedingNode'
234bool wxXmlNode::InsertChildAfter(wxXmlNode *child, wxXmlNode *precedingNode)
235{
236 wxCHECK_MSG( child, false, "cannot insert a NULL node!" );
237 wxCHECK_MSG( child->m_parent == NULL, false, "node already has a parent" );
238 wxCHECK_MSG( child->m_next == NULL, false, "node already has m_next" );
239 wxCHECK_MSG( precedingNode == NULL || precedingNode->m_parent == this, false,
240 "precedingNode has wrong parent" );
241
242 if ( precedingNode )
243 {
244 child->m_next = precedingNode->m_next;
245 precedingNode->m_next = child;
246 }
247 else // precedingNode == NULL
248 {
249 wxCHECK_MSG( m_children == NULL, false,
250 "NULL precedingNode only makes sense when there are no children" );
251
252 child->m_next = m_children;
253 m_children = child;
254 }
255
256 child->m_parent = this;
257 return true;
258}
259
27b0c286
VS
260bool wxXmlNode::RemoveChild(wxXmlNode *child)
261{
262 if (m_children == NULL)
759f7272 263 return false;
27b0c286
VS
264 else if (m_children == child)
265 {
266 m_children = child->m_next;
267 child->m_parent = NULL;
268 child->m_next = NULL;
759f7272 269 return true;
27b0c286
VS
270 }
271 else
272 {
273 wxXmlNode *ch = m_children;
274 while (ch->m_next)
275 {
276 if (ch->m_next == child)
277 {
278 ch->m_next = child->m_next;
279 child->m_parent = NULL;
280 child->m_next = NULL;
759f7272 281 return true;
27b0c286
VS
282 }
283 ch = ch->m_next;
284 }
759f7272 285 return false;
27b0c286
VS
286 }
287}
288
e13ce4a3
VZ
289void wxXmlNode::AddAttribute(const wxString& name, const wxString& value)
290{
291 AddProperty(name, value);
292}
293
294void wxXmlNode::AddAttribute(wxXmlAttribute *attr)
295{
296 AddProperty(attr);
297}
298
299bool wxXmlNode::DeleteAttribute(const wxString& name)
300{
301 return DeleteProperty(name);
302}
303
27b0c286
VS
304void wxXmlNode::AddProperty(const wxString& name, const wxString& value)
305{
288b6107 306 AddProperty(new wxXmlAttribute(name, value, NULL));
27b0c286
VS
307}
308
288b6107 309void wxXmlNode::AddProperty(wxXmlAttribute *attr)
27b0c286 310{
288b6107
VS
311 if (m_attrs == NULL)
312 m_attrs = attr;
27b0c286
VS
313 else
314 {
288b6107 315 wxXmlAttribute *p = m_attrs;
27b0c286 316 while (p->GetNext()) p = p->GetNext();
288b6107 317 p->SetNext(attr);
27b0c286
VS
318 }
319}
320
321bool wxXmlNode::DeleteProperty(const wxString& name)
322{
288b6107 323 wxXmlAttribute *attr;
27b0c286 324
288b6107 325 if (m_attrs == NULL)
759f7272 326 return false;
27b0c286 327
288b6107 328 else if (m_attrs->GetName() == name)
27b0c286 329 {
288b6107
VS
330 attr = m_attrs;
331 m_attrs = attr->GetNext();
332 attr->SetNext(NULL);
333 delete attr;
759f7272 334 return true;
27b0c286
VS
335 }
336
337 else
338 {
288b6107 339 wxXmlAttribute *p = m_attrs;
27b0c286
VS
340 while (p->GetNext())
341 {
342 if (p->GetNext()->GetName() == name)
343 {
288b6107
VS
344 attr = p->GetNext();
345 p->SetNext(attr->GetNext());
346 attr->SetNext(NULL);
347 delete attr;
759f7272 348 return true;
27b0c286
VS
349 }
350 p = p->GetNext();
351 }
759f7272 352 return false;
27b0c286
VS
353 }
354}
355
4c43dd90
JS
356wxString wxXmlNode::GetNodeContent() const
357{
358 wxXmlNode *n = GetChildren();
359
360 while (n)
361 {
362 if (n->GetType() == wxXML_TEXT_NODE ||
363 n->GetType() == wxXML_CDATA_SECTION_NODE)
364 return n->GetContent();
365 n = n->GetNext();
366 }
367 return wxEmptyString;
368}
369
538f3830
VS
370int wxXmlNode::GetDepth(wxXmlNode *grandparent) const
371{
372 const wxXmlNode *n = this;
373 int ret = -1;
374
375 do
376 {
377 ret++;
378 n = n->GetParent();
379 if (n == grandparent)
380 return ret;
381
382 } while (n);
383
384 return wxNOT_FOUND;
385}
386
387bool wxXmlNode::IsWhitespaceOnly() const
388{
389 return wxIsWhiteOnly(m_content);
390}
391
27b0c286
VS
392
393
394//-----------------------------------------------------------------------------
395// wxXmlDocument
396//-----------------------------------------------------------------------------
397
398wxXmlDocument::wxXmlDocument()
e767076e 399 : m_version(wxS("1.0")), m_fileEncoding(wxS("utf-8")), m_root(NULL)
27b0c286
VS
400{
401#if !wxUSE_UNICODE
e767076e 402 m_encoding = wxS("UTF-8");
27b0c286
VS
403#endif
404}
405
406wxXmlDocument::wxXmlDocument(const wxString& filename, const wxString& encoding)
d0468e8c 407 :wxObject(), m_root(NULL)
27b0c286
VS
408{
409 if ( !Load(filename, encoding) )
410 {
411 wxDELETE(m_root);
412 }
413}
414
415wxXmlDocument::wxXmlDocument(wxInputStream& stream, const wxString& encoding)
d0468e8c 416 :wxObject(), m_root(NULL)
27b0c286
VS
417{
418 if ( !Load(stream, encoding) )
419 {
420 wxDELETE(m_root);
421 }
422}
423
424wxXmlDocument::wxXmlDocument(const wxXmlDocument& doc)
d0468e8c 425 :wxObject()
27b0c286
VS
426{
427 DoCopy(doc);
428}
429
430wxXmlDocument& wxXmlDocument::operator=(const wxXmlDocument& doc)
431{
432 wxDELETE(m_root);
433 DoCopy(doc);
434 return *this;
435}
436
437void wxXmlDocument::DoCopy(const wxXmlDocument& doc)
438{
439 m_version = doc.m_version;
440#if !wxUSE_UNICODE
441 m_encoding = doc.m_encoding;
442#endif
443 m_fileEncoding = doc.m_fileEncoding;
e8da6b7c
RR
444
445 if (doc.m_root)
446 m_root = new wxXmlNode(*doc.m_root);
447 else
448 m_root = NULL;
27b0c286
VS
449}
450
538f3830 451bool wxXmlDocument::Load(const wxString& filename, const wxString& encoding, int flags)
27b0c286
VS
452{
453 wxFileInputStream stream(filename);
97757cee
VZ
454 if (!stream.Ok())
455 return false;
538f3830 456 return Load(stream, encoding, flags);
27b0c286
VS
457}
458
538f3830 459bool wxXmlDocument::Save(const wxString& filename, int indentstep) const
27b0c286
VS
460{
461 wxFileOutputStream stream(filename);
97757cee
VZ
462 if (!stream.Ok())
463 return false;
538f3830 464 return Save(stream, indentstep);
27b0c286
VS
465}
466
467
468
469//-----------------------------------------------------------------------------
470// wxXmlDocument loading routines
471//-----------------------------------------------------------------------------
472
ddae497f
VZ
473// converts Expat-produced string in UTF-8 into wxString using the specified
474// conv or keep in UTF-8 if conv is NULL
475static wxString CharToString(wxMBConv *conv,
b04edcaf 476 const char *s, size_t len = wxString::npos)
27b0c286 477{
b04edcaf 478#if !wxUSE_UNICODE
27b0c286
VS
479 if ( conv )
480 {
ddae497f
VZ
481 // there can be no embedded NULs in this string so we don't need the
482 // output length, it will be NUL-terminated
483 const wxWCharBuffer wbuf(
6df6e35a 484 wxConvUTF8.cMB2WC(s, len == wxString::npos ? wxNO_LEN : len, NULL));
ddae497f 485
da452b9e 486 return wxString(wbuf, *conv);
27b0c286 487 }
b04edcaf
VS
488 // else: the string is wanted in UTF-8
489#endif // !wxUSE_UNICODE
490
491 wxUnusedVar(conv);
cc209a51 492 return wxString::FromUTF8Unchecked(s, len);
27b0c286
VS
493}
494
538f3830 495// returns true if the given string contains only whitespaces
352d9b89 496bool wxIsWhiteOnly(const wxString& buf)
538f3830 497{
352d9b89
VS
498 for ( wxString::const_iterator i = buf.begin(); i != buf.end(); ++i )
499 {
500 wxChar c = *i;
e767076e 501 if ( c != wxS(' ') && c != wxS('\t') && c != wxS('\n') && c != wxS('\r'))
538f3830 502 return false;
352d9b89 503 }
538f3830
VS
504 return true;
505}
506
507
27b0c286
VS
508struct wxXmlParsingContext
509{
43a302f2
VS
510 wxXmlParsingContext()
511 : conv(NULL),
512 root(NULL),
513 node(NULL),
514 lastChild(NULL),
515 lastAsText(NULL),
516 removeWhiteOnlyNodes(false)
517 {}
518
6e26d6b7 519 XML_Parser parser;
27b0c286
VS
520 wxMBConv *conv;
521 wxXmlNode *root;
43a302f2
VS
522 wxXmlNode *node; // the node being parsed
523 wxXmlNode *lastChild; // the last child of "node"
524 wxXmlNode *lastAsText; // the last _text_ child of "node"
27b0c286
VS
525 wxString encoding;
526 wxString version;
538f3830 527 bool removeWhiteOnlyNodes;
27b0c286
VS
528};
529
43a302f2
VS
530// checks that ctx->lastChild is in consistent state
531#define ASSERT_LAST_CHILD_OK(ctx) \
532 wxASSERT( ctx->lastChild == NULL || \
533 ctx->lastChild->GetNext() == NULL ); \
534 wxASSERT( ctx->lastChild == NULL || \
535 ctx->lastChild->GetParent() == ctx->node )
536
865bb325 537extern "C" {
27b0c286
VS
538static void StartElementHnd(void *userData, const char *name, const char **atts)
539{
540 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
6e26d6b7
VS
541 wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE,
542 CharToString(ctx->conv, name),
543 wxEmptyString,
544 XML_GetCurrentLineNumber(ctx->parser));
27b0c286 545 const char **a = atts;
6e26d6b7 546
43a302f2 547 // add node attributes
27b0c286
VS
548 while (*a)
549 {
288b6107 550 node->AddAttribute(CharToString(ctx->conv, a[0]), CharToString(ctx->conv, a[1]));
27b0c286
VS
551 a += 2;
552 }
43a302f2 553
27b0c286 554 if (ctx->root == NULL)
43a302f2 555 {
27b0c286 556 ctx->root = node;
43a302f2 557 }
27b0c286 558 else
43a302f2
VS
559 {
560 ASSERT_LAST_CHILD_OK(ctx);
561 ctx->node->InsertChildAfter(node, ctx->lastChild);
562 }
563
27b0c286 564 ctx->lastAsText = NULL;
43a302f2
VS
565 ctx->lastChild = NULL; // our new node "node" has no children yet
566
567 ctx->node = node;
27b0c286
VS
568}
569
570static void EndElementHnd(void *userData, const char* WXUNUSED(name))
571{
572 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
573
43a302f2
VS
574 // we're exiting the last children of ctx->node->GetParent() and going
575 // back one level up, so current value of ctx->node points to the last
576 // child of ctx->node->GetParent()
577 ctx->lastChild = ctx->node;
578
27b0c286
VS
579 ctx->node = ctx->node->GetParent();
580 ctx->lastAsText = NULL;
581}
582
583static void TextHnd(void *userData, const char *s, int len)
584{
585 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
538f3830 586 wxString str = CharToString(ctx->conv, s, len);
27b0c286
VS
587
588 if (ctx->lastAsText)
589 {
d6cb1287 590 ctx->lastAsText->SetContent(ctx->lastAsText->GetContent() + str);
27b0c286
VS
591 }
592 else
593 {
538f3830
VS
594 bool whiteOnly = false;
595 if (ctx->removeWhiteOnlyNodes)
596 whiteOnly = wxIsWhiteOnly(str);
597
27b0c286
VS
598 if (!whiteOnly)
599 {
43a302f2 600 wxXmlNode *textnode =
e767076e 601 new wxXmlNode(wxXML_TEXT_NODE, wxS("text"), str,
6e26d6b7 602 XML_GetCurrentLineNumber(ctx->parser));
43a302f2
VS
603
604 ASSERT_LAST_CHILD_OK(ctx);
605 ctx->node->InsertChildAfter(textnode, ctx->lastChild);
606 ctx->lastChild= ctx->lastAsText = textnode;
27b0c286
VS
607 }
608 }
27b0c286
VS
609}
610
a01cbf0a
RR
611static void StartCdataHnd(void *userData)
612{
613 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
614
43a302f2 615 wxXmlNode *textnode =
e767076e 616 new wxXmlNode(wxXML_CDATA_SECTION_NODE, wxS("cdata"), wxS(""),
6e26d6b7 617 XML_GetCurrentLineNumber(ctx->parser));
43a302f2
VS
618
619 ASSERT_LAST_CHILD_OK(ctx);
620 ctx->node->InsertChildAfter(textnode, ctx->lastChild);
621 ctx->lastChild= ctx->lastAsText = textnode;
a01cbf0a 622}
a01cbf0a 623
a6cf6bcf
VZ
624static void EndCdataHnd(void *userData)
625{
626 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
627
628 // we need to reset this pointer so that subsequent text nodes don't append
629 // their contents to this one but create new wxXML_TEXT_NODE objects (or
630 // not create anything at all if only white space follows the CDATA section
631 // and wxXMLDOC_KEEP_WHITESPACE_NODES is not used as is commonly the case)
632 ctx->lastAsText = NULL;
633}
634
27b0c286
VS
635static void CommentHnd(void *userData, const char *data)
636{
637 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
638
639 if (ctx->node)
640 {
43a302f2 641 wxXmlNode *commentnode =
6e26d6b7 642 new wxXmlNode(wxXML_COMMENT_NODE,
e767076e 643 wxS("comment"), CharToString(ctx->conv, data),
43a302f2
VS
644 XML_GetCurrentLineNumber(ctx->parser));
645
646 ASSERT_LAST_CHILD_OK(ctx);
647 ctx->node->InsertChildAfter(commentnode, ctx->lastChild);
648 ctx->lastChild = commentnode;
27b0c286 649 }
43a302f2
VS
650 //else: ctx->node == NULL happens if there is a comment before
651 // the root element. We current don't have a way to represent
652 // these in wxXmlDocument (FIXME).
653
27b0c286
VS
654 ctx->lastAsText = NULL;
655}
656
657static void DefaultHnd(void *userData, const char *s, int len)
658{
659 // XML header:
660 if (len > 6 && memcmp(s, "<?xml ", 6) == 0)
661 {
662 wxXmlParsingContext *ctx = (wxXmlParsingContext*)userData;
663
664 wxString buf = CharToString(ctx->conv, s, (size_t)len);
665 int pos;
e767076e 666 pos = buf.Find(wxS("encoding="));
27b0c286
VS
667 if (pos != wxNOT_FOUND)
668 ctx->encoding = buf.Mid(pos + 10).BeforeFirst(buf[(size_t)pos+9]);
e767076e 669 pos = buf.Find(wxS("version="));
27b0c286
VS
670 if (pos != wxNOT_FOUND)
671 ctx->version = buf.Mid(pos + 9).BeforeFirst(buf[(size_t)pos+8]);
672 }
673}
674
675static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData),
676 const XML_Char *name, XML_Encoding *info)
677{
678 // We must build conversion table for expat. The easiest way to do so
679 // is to let wxCSConv convert as string containing all characters to
680 // wide character representation:
86501081 681 wxCSConv conv(name);
27b0c286
VS
682 char mbBuf[2];
683 wchar_t wcBuf[10];
684 size_t i;
685
686 mbBuf[1] = 0;
687 info->map[0] = 0;
688 for (i = 0; i < 255; i++)
689 {
690 mbBuf[0] = (char)(i+1);
691 if (conv.MB2WC(wcBuf, mbBuf, 2) == (size_t)-1)
692 {
693 // invalid/undefined byte in the encoding:
694 info->map[i+1] = -1;
695 }
696 info->map[i+1] = (int)wcBuf[0];
697 }
42841dfc 698
27b0c286
VS
699 info->data = NULL;
700 info->convert = NULL;
701 info->release = NULL;
702
703 return 1;
704}
26296ac9
VS
705
706} // extern "C"
27b0c286 707
538f3830 708bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding, int flags)
27b0c286
VS
709{
710#if wxUSE_UNICODE
711 (void)encoding;
712#else
713 m_encoding = encoding;
714#endif
715
716 const size_t BUFSIZE = 1024;
717 char buf[BUFSIZE];
718 wxXmlParsingContext ctx;
719 bool done;
720 XML_Parser parser = XML_ParserCreate(NULL);
721
e767076e 722 ctx.encoding = wxS("UTF-8"); // default in absence of encoding=""
27b0c286
VS
723 ctx.conv = NULL;
724#if !wxUSE_UNICODE
e767076e 725 if ( encoding.CmpNoCase(wxS("UTF-8")) != 0 )
27b0c286
VS
726 ctx.conv = new wxCSConv(encoding);
727#endif
538f3830 728 ctx.removeWhiteOnlyNodes = (flags & wxXMLDOC_KEEP_WHITESPACE_NODES) == 0;
6e26d6b7 729 ctx.parser = parser;
27b0c286
VS
730
731 XML_SetUserData(parser, (void*)&ctx);
732 XML_SetElementHandler(parser, StartElementHnd, EndElementHnd);
733 XML_SetCharacterDataHandler(parser, TextHnd);
a6cf6bcf 734 XML_SetCdataSectionHandler(parser, StartCdataHnd, EndCdataHnd);;
27b0c286
VS
735 XML_SetCommentHandler(parser, CommentHnd);
736 XML_SetDefaultHandler(parser, DefaultHnd);
737 XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL);
738
739 bool ok = true;
740 do
741 {
742 size_t len = stream.Read(buf, BUFSIZE).LastRead();
743 done = (len < BUFSIZE);
744 if (!XML_Parse(parser, buf, len, done))
745 {
6a8fb6bd
VS
746 wxString error(XML_ErrorString(XML_GetErrorCode(parser)),
747 *wxConvCurrent);
27b0c286 748 wxLogError(_("XML parsing error: '%s' at line %d"),
6a8fb6bd 749 error.c_str(),
936759a4 750 (int)XML_GetCurrentLineNumber(parser));
27b0c286
VS
751 ok = false;
752 break;
753 }
754 } while (!done);
755
756 if (ok)
757 {
759f7272 758 if (!ctx.version.empty())
6a8fb6bd 759 SetVersion(ctx.version);
759f7272 760 if (!ctx.encoding.empty())
6a8fb6bd 761 SetFileEncoding(ctx.encoding);
27b0c286
VS
762 SetRoot(ctx.root);
763 }
6a8fb6bd
VS
764 else
765 {
766 delete ctx.root;
767 }
27b0c286
VS
768
769 XML_ParserFree(parser);
770#if !wxUSE_UNICODE
771 if ( ctx.conv )
772 delete ctx.conv;
773#endif
774
775 return ok;
776
777}
778
779
780
781//-----------------------------------------------------------------------------
782// wxXmlDocument saving routines
783//-----------------------------------------------------------------------------
784
e767076e
VZ
785// helpers for XML generation
786namespace
787{
788
27b0c286 789// write string to output:
e767076e
VZ
790bool OutputString(wxOutputStream& stream,
791 const wxString& str,
792 wxMBConv *convMem,
793 wxMBConv *convFile)
27b0c286 794{
8dfd4fad 795 if (str.empty())
e767076e 796 return true;
8dfd4fad 797
27b0c286 798#if wxUSE_UNICODE
8dfd4fad 799 wxUnusedVar(convMem);
a6ed2786
VZ
800 if ( !convFile )
801 convFile = &wxConvUTF8;
f13d956e 802
a6ed2786
VZ
803 const wxScopedCharBuffer buf(str.mb_str(*convFile));
804 if ( !buf.length() )
805 {
806 // conversion failed, can't write this string in an XML file in this
807 // (presumably non-UTF-8) encoding
e767076e 808 return false;
a6ed2786 809 }
e767076e 810
a6ed2786 811 stream.Write(buf, buf.length());
8dfd4fad
VZ
812#else // !wxUSE_UNICODE
813 if ( convFile && convMem )
27b0c286
VS
814 {
815 wxString str2(str.wc_str(*convMem), *convFile);
e767076e 816 stream.Write(str2.mb_str(), str2.length());
27b0c286 817 }
8dfd4fad
VZ
818 else // no conversions to do
819 {
e767076e 820 stream.Write(str.mb_str(), str.length());
8dfd4fad
VZ
821 }
822#endif // wxUSE_UNICODE/!wxUSE_UNICODE
e767076e
VZ
823
824 return stream.IsOk();
27b0c286
VS
825}
826
926649a9 827enum EscapingMode
8dfd4fad 828{
926649a9
VS
829 Escape_Text,
830 Escape_Attribute
8dfd4fad
VZ
831};
832
27b0c286 833// Same as above, but create entities first.
926649a9
VS
834// Translates '<' to "&lt;", '>' to "&gt;" and so on, according to the spec:
835// http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
836bool OutputEscapedString(wxOutputStream& stream,
837 const wxString& str,
838 wxMBConv *convMem,
839 wxMBConv *convFile,
840 EscapingMode mode)
841{
842 wxString escaped;
843 escaped.reserve(str.length());
e767076e 844
926649a9
VS
845 for ( wxString::const_iterator i = str.begin(); i != str.end(); ++i )
846 {
847 const wxChar c = *i;
e767076e 848
926649a9
VS
849 switch ( c )
850 {
851 case wxS('<'):
852 escaped.append(wxS("&lt;"));
853 break;
854 case wxS('>'):
855 escaped.append(wxS("&gt;"));
856 break;
857 case wxS('&'):
858 escaped.append(wxS("&amp;"));
859 break;
860 case wxS('\r'):
861 escaped.append(wxS("&#xD;"));
862 break;
863 default:
864 if ( mode == Escape_Attribute )
865 {
866 switch ( c )
867 {
868 case wxS('"'):
869 escaped.append(wxS("&quot;"));
870 break;
871 case wxS('\t'):
872 escaped.append(wxS("&#x9;"));
873 break;
874 case wxS('\n'):
875 escaped.append(wxS("&#xA;"));
876 break;
877 default:
878 escaped.append(c);
879 }
880
881 }
882 else
883 {
884 escaped.append(c);
885 }
27b0c286
VS
886 }
887 }
e767076e 888
926649a9 889 return OutputString(stream, escaped, convMem, convFile);
27b0c286
VS
890}
891
e767076e
VZ
892bool OutputIndentation(wxOutputStream& stream,
893 int indent,
894 wxMBConv *convMem,
895 wxMBConv *convFile)
27b0c286 896{
e767076e 897 wxString str(wxS("\n"));
57cc93eb 898 str += wxString(indent, wxS(' '));
e767076e 899 return OutputString(stream, str, convMem, convFile);
27b0c286
VS
900}
901
e767076e
VZ
902bool OutputNode(wxOutputStream& stream,
903 wxXmlNode *node,
904 int indent,
905 wxMBConv *convMem,
906 wxMBConv *convFile,
907 int indentstep)
27b0c286 908{
e767076e 909 bool rc;
27b0c286
VS
910 switch (node->GetType())
911 {
eac789ff 912 case wxXML_CDATA_SECTION_NODE:
e767076e
VZ
913 rc = OutputString(stream, wxS("<![CDATA["), convMem, convFile) &&
914 OutputString(stream, node->GetContent(), convMem, convFile) &&
915 OutputString(stream, wxS("]]>"), convMem, convFile);
eac789ff 916 break;
a01cbf0a 917
27b0c286 918 case wxXML_TEXT_NODE:
30f6914b
JS
919 if (node->GetNoConversion())
920 {
921 stream.Write(node->GetContent().c_str(), node->GetContent().Length());
922 rc = true;
923 }
924 else
925 rc = OutputEscapedString(stream, node->GetContent(),
926649a9
VS
926 convMem, convFile,
927 Escape_Text);
27b0c286
VS
928 break;
929
930 case wxXML_ELEMENT_NODE:
e767076e
VZ
931 rc = OutputString(stream, wxS("<"), convMem, convFile) &&
932 OutputString(stream, node->GetName(), convMem, convFile);
27b0c286 933
e767076e 934 if ( rc )
27b0c286 935 {
e767076e
VZ
936 for ( wxXmlAttribute *attr = node->GetAttributes();
937 attr && rc;
938 attr = attr->GetNext() )
939 {
940 rc = OutputString(stream,
941 wxS(" ") + attr->GetName() + wxS("=\""),
942 convMem, convFile) &&
926649a9
VS
943 OutputEscapedString(stream, attr->GetValue(),
944 convMem, convFile,
945 Escape_Attribute) &&
e767076e
VZ
946 OutputString(stream, wxS("\""), convMem, convFile);
947 }
27b0c286
VS
948 }
949
e767076e 950 if ( node->GetChildren() )
27b0c286 951 {
e767076e
VZ
952 rc = OutputString(stream, wxS(">"), convMem, convFile);
953
954 wxXmlNode *prev = NULL;
955 for ( wxXmlNode *n = node->GetChildren();
956 n && rc;
957 n = n->GetNext() )
27b0c286 958 {
e767076e
VZ
959 if ( indentstep >= 0 && n->GetType() != wxXML_TEXT_NODE )
960 {
961 rc = OutputIndentation(stream, indent + indentstep,
962 convMem, convFile);
963 }
964
965 if ( rc )
966 rc = OutputNode(stream, n, indent + indentstep,
967 convMem, convFile, indentstep);
968
27b0c286 969 prev = n;
27b0c286 970 }
e767076e
VZ
971
972 if ( rc && indentstep >= 0 &&
973 prev && prev->GetType() != wxXML_TEXT_NODE )
974 {
975 rc = OutputIndentation(stream, indent, convMem, convFile);
976 }
977
978 if ( rc )
979 {
980 rc = OutputString(stream, wxS("</"), convMem, convFile) &&
981 OutputString(stream, node->GetName(),
982 convMem, convFile) &&
983 OutputString(stream, wxS(">"), convMem, convFile);
984 }
985 }
986 else // no children, output "<foo/>"
987 {
988 rc = OutputString(stream, wxS("/>"), convMem, convFile);
27b0c286 989 }
27b0c286
VS
990 break;
991
992 case wxXML_COMMENT_NODE:
e767076e
VZ
993 rc = OutputString(stream, wxS("<!--"), convMem, convFile) &&
994 OutputString(stream, node->GetContent(), convMem, convFile) &&
995 OutputString(stream, wxS("-->"), convMem, convFile);
27b0c286
VS
996 break;
997
998 default:
e767076e
VZ
999 wxFAIL_MSG("unsupported node type");
1000 rc = false;
27b0c286 1001 }
e767076e
VZ
1002
1003 return rc;
27b0c286
VS
1004}
1005
e767076e
VZ
1006} // anonymous namespace
1007
538f3830 1008bool wxXmlDocument::Save(wxOutputStream& stream, int indentstep) const
27b0c286
VS
1009{
1010 if ( !IsOk() )
759f7272 1011 return false;
27b0c286 1012
e767076e 1013 wxScopedPtr<wxMBConv> convMem, convFile;
759f7272 1014
27b0c286 1015#if wxUSE_UNICODE
e767076e 1016 convFile.reset(new wxCSConv(GetFileEncoding()));
27b0c286 1017#else
8605f9c5 1018 if ( GetFileEncoding().CmpNoCase(GetEncoding()) != 0 )
27b0c286 1019 {
e767076e
VZ
1020 convFile.reset(new wxCSConv(GetFileEncoding()));
1021 convMem.reset(new wxCSConv(GetEncoding()));
8605f9c5 1022 }
e767076e 1023 //else: file and in-memory encodings are the same, no conversion needed
27b0c286
VS
1024#endif
1025
e767076e
VZ
1026 return OutputString(stream,
1027 wxString::Format
1028 (
1029 wxS("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
1030 GetVersion(), GetFileEncoding()
1031 ),
1032 convMem.get(),
1033 convFile.get()) &&
1034 OutputNode(stream, GetRoot(), 0,
1035 convMem.get(), convFile.get(), indentstep) &&
1036 OutputString(stream, wxS("\n"), convMem.get(), convFile.get());
27b0c286
VS
1037}
1038
ccec9093
VZ
1039/*static*/ wxVersionInfo wxXmlDocument::GetLibraryVersionInfo()
1040{
1041 return wxVersionInfo("expat",
1042 XML_MAJOR_VERSION,
1043 XML_MINOR_VERSION,
1044 XML_MICRO_VERSION);
1045}
1046
27b0c286 1047#endif // wxUSE_XML