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