1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/xml/xml.cpp
3 // Purpose: wxXmlDocument - XML parser & data holder class
4 // Author: Vaclav Slavik
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
20 #include "wx/xml/xml.h"
28 #include "wx/wfstream.h"
29 #include "wx/datstrm.h"
30 #include "wx/zstream.h"
31 #include "wx/strconv.h"
33 #include "expat.h" // from Expat
35 // DLL options compatibility check:
36 WX_CHECK_BUILD_OPTIONS("wxXML")
39 IMPLEMENT_CLASS(wxXmlDocument
, wxObject
)
42 // a private utility used by wxXML
43 static bool wxIsWhiteOnly(const wxString
& buf
);
46 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
50 wxXmlNode::wxXmlNode(wxXmlNode
*parent
,wxXmlNodeType type
,
51 const wxString
& name
, const wxString
& content
,
52 wxXmlAttribute
*attrs
, wxXmlNode
*next
, int lineNo
)
53 : m_type(type
), m_name(name
), m_content(content
),
54 m_attrs(attrs
), m_parent(parent
),
55 m_children(NULL
), m_next(next
),
60 if (m_parent
->m_children
)
62 m_next
= m_parent
->m_children
;
63 m_parent
->m_children
= this;
66 m_parent
->m_children
= this;
70 wxXmlNode::wxXmlNode(wxXmlNodeType type
, const wxString
& name
,
71 const wxString
& content
,
73 : m_type(type
), m_name(name
), m_content(content
),
74 m_attrs(NULL
), m_parent(NULL
),
75 m_children(NULL
), m_next(NULL
),
79 wxXmlNode::wxXmlNode(const wxXmlNode
& node
)
86 wxXmlNode::~wxXmlNode()
89 for (c
= m_children
; c
; c
= c2
)
95 wxXmlAttribute
*p
, *p2
;
96 for (p
= m_attrs
; p
; p
= p2
)
103 wxXmlNode
& wxXmlNode::operator=(const wxXmlNode
& node
)
106 wxDELETE(m_children
);
111 void wxXmlNode::DoCopy(const wxXmlNode
& node
)
113 m_type
= node
.m_type
;
114 m_name
= node
.m_name
;
115 m_content
= node
.m_content
;
116 m_lineNo
= node
.m_lineNo
;
119 wxXmlNode
*n
= node
.m_children
;
122 AddChild(new wxXmlNode(*n
));
127 wxXmlAttribute
*p
= node
.m_attrs
;
130 AddAttribute(p
->GetName(), p
->GetValue());
135 bool wxXmlNode::HasAttribute(const wxString
& attrName
) const
137 wxXmlAttribute
*attr
= GetAttributes();
141 if (attr
->GetName() == attrName
) return true;
142 attr
= attr
->GetNext();
148 bool wxXmlNode::GetAttribute(const wxString
& attrName
, wxString
*value
) const
150 wxCHECK_MSG( value
, false, "value argument must not be NULL" );
152 wxXmlAttribute
*attr
= GetAttributes();
156 if (attr
->GetName() == attrName
)
158 *value
= attr
->GetValue();
161 attr
= attr
->GetNext();
167 wxString
wxXmlNode::GetAttribute(const wxString
& attrName
, const wxString
& defaultVal
) const
170 if (GetAttribute(attrName
, &tmp
))
176 void wxXmlNode::AddChild(wxXmlNode
*child
)
178 if (m_children
== NULL
)
182 wxXmlNode
*ch
= m_children
;
183 while (ch
->m_next
) ch
= ch
->m_next
;
186 child
->m_next
= NULL
;
187 child
->m_parent
= this;
190 bool wxXmlNode::InsertChild(wxXmlNode
*child
, wxXmlNode
*before_node
)
192 wxCHECK_MSG(before_node
== NULL
|| before_node
->GetParent() == this, false,
193 wxT("wxXmlNode::InsertChild - the node has incorrect parent"));
194 wxCHECK_MSG(child
, false, wxT("Cannot insert a NULL pointer!"));
196 if (m_children
== before_node
)
198 else if (m_children
== NULL
)
200 if (before_node
!= NULL
)
201 return false; // we have no children so we don't need to search
204 else if (before_node
== NULL
)
207 child
->m_parent
= this;
208 child
->m_next
= m_children
;
214 wxXmlNode
*ch
= m_children
;
215 while (ch
&& ch
->m_next
!= before_node
) ch
= ch
->m_next
;
217 return false; // before_node not found
221 child
->m_parent
= this;
222 child
->m_next
= before_node
;
226 bool wxXmlNode::RemoveChild(wxXmlNode
*child
)
228 if (m_children
== NULL
)
230 else if (m_children
== child
)
232 m_children
= child
->m_next
;
233 child
->m_parent
= NULL
;
234 child
->m_next
= NULL
;
239 wxXmlNode
*ch
= m_children
;
242 if (ch
->m_next
== child
)
244 ch
->m_next
= child
->m_next
;
245 child
->m_parent
= NULL
;
246 child
->m_next
= NULL
;
255 void wxXmlNode::AddProperty(const wxString
& name
, const wxString
& value
)
257 AddProperty(new wxXmlAttribute(name
, value
, NULL
));
260 void wxXmlNode::AddProperty(wxXmlAttribute
*attr
)
266 wxXmlAttribute
*p
= m_attrs
;
267 while (p
->GetNext()) p
= p
->GetNext();
272 bool wxXmlNode::DeleteProperty(const wxString
& name
)
274 wxXmlAttribute
*attr
;
279 else if (m_attrs
->GetName() == name
)
282 m_attrs
= attr
->GetNext();
290 wxXmlAttribute
*p
= m_attrs
;
293 if (p
->GetNext()->GetName() == name
)
296 p
->SetNext(attr
->GetNext());
307 wxString
wxXmlNode::GetNodeContent() const
309 wxXmlNode
*n
= GetChildren();
313 if (n
->GetType() == wxXML_TEXT_NODE
||
314 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
315 return n
->GetContent();
318 return wxEmptyString
;
321 int wxXmlNode::GetDepth(wxXmlNode
*grandparent
) const
323 const wxXmlNode
*n
= this;
330 if (n
== grandparent
)
338 bool wxXmlNode::IsWhitespaceOnly() const
340 return wxIsWhiteOnly(m_content
);
345 //-----------------------------------------------------------------------------
347 //-----------------------------------------------------------------------------
349 wxXmlDocument::wxXmlDocument()
350 : m_version(wxT("1.0")), m_fileEncoding(wxT("utf-8")), m_root(NULL
)
353 m_encoding
= wxT("UTF-8");
357 wxXmlDocument::wxXmlDocument(const wxString
& filename
, const wxString
& encoding
)
358 :wxObject(), m_root(NULL
)
360 if ( !Load(filename
, encoding
) )
366 wxXmlDocument::wxXmlDocument(wxInputStream
& stream
, const wxString
& encoding
)
367 :wxObject(), m_root(NULL
)
369 if ( !Load(stream
, encoding
) )
375 wxXmlDocument::wxXmlDocument(const wxXmlDocument
& doc
)
381 wxXmlDocument
& wxXmlDocument::operator=(const wxXmlDocument
& doc
)
388 void wxXmlDocument::DoCopy(const wxXmlDocument
& doc
)
390 m_version
= doc
.m_version
;
392 m_encoding
= doc
.m_encoding
;
394 m_fileEncoding
= doc
.m_fileEncoding
;
397 m_root
= new wxXmlNode(*doc
.m_root
);
402 bool wxXmlDocument::Load(const wxString
& filename
, const wxString
& encoding
, int flags
)
404 wxFileInputStream
stream(filename
);
407 return Load(stream
, encoding
, flags
);
410 bool wxXmlDocument::Save(const wxString
& filename
, int indentstep
) const
412 wxFileOutputStream
stream(filename
);
415 return Save(stream
, indentstep
);
420 //-----------------------------------------------------------------------------
421 // wxXmlDocument loading routines
422 //-----------------------------------------------------------------------------
424 // converts Expat-produced string in UTF-8 into wxString using the specified
425 // conv or keep in UTF-8 if conv is NULL
426 static wxString
CharToString(wxMBConv
*conv
,
427 const char *s
, size_t len
= wxString::npos
)
432 // there can be no embedded NULs in this string so we don't need the
433 // output length, it will be NUL-terminated
434 const wxWCharBuffer
wbuf(
435 wxConvUTF8
.cMB2WC(s
, len
== wxString::npos
? wxNO_LEN
: len
, NULL
));
437 return wxString(wbuf
, *conv
);
439 // else: the string is wanted in UTF-8
440 #endif // !wxUSE_UNICODE
443 return wxString::FromUTF8(s
, len
);
446 // returns true if the given string contains only whitespaces
447 bool wxIsWhiteOnly(const wxString
& buf
)
449 for ( wxString::const_iterator i
= buf
.begin(); i
!= buf
.end(); ++i
)
452 if ( c
!= wxT(' ') && c
!= wxT('\t') && c
!= wxT('\n') && c
!= wxT('\r'))
459 struct wxXmlParsingContext
465 wxXmlNode
*lastAsText
;
468 bool removeWhiteOnlyNodes
;
472 static void StartElementHnd(void *userData
, const char *name
, const char **atts
)
474 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
475 wxXmlNode
*node
= new wxXmlNode(wxXML_ELEMENT_NODE
,
476 CharToString(ctx
->conv
, name
),
478 XML_GetCurrentLineNumber(ctx
->parser
));
479 const char **a
= atts
;
483 node
->AddAttribute(CharToString(ctx
->conv
, a
[0]), CharToString(ctx
->conv
, a
[1]));
486 if (ctx
->root
== NULL
)
489 ctx
->node
->AddChild(node
);
491 ctx
->lastAsText
= NULL
;
494 static void EndElementHnd(void *userData
, const char* WXUNUSED(name
))
496 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
498 ctx
->node
= ctx
->node
->GetParent();
499 ctx
->lastAsText
= NULL
;
502 static void TextHnd(void *userData
, const char *s
, int len
)
504 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
505 wxString str
= CharToString(ctx
->conv
, s
, len
);
509 ctx
->lastAsText
->SetContent(ctx
->lastAsText
->GetContent() + str
);
513 bool whiteOnly
= false;
514 if (ctx
->removeWhiteOnlyNodes
)
515 whiteOnly
= wxIsWhiteOnly(str
);
520 new wxXmlNode(wxXML_TEXT_NODE
, wxT("text"), str
,
521 XML_GetCurrentLineNumber(ctx
->parser
));
522 ctx
->node
->AddChild(ctx
->lastAsText
);
527 static void StartCdataHnd(void *userData
)
529 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
532 new wxXmlNode(wxXML_CDATA_SECTION_NODE
, wxT("cdata"), wxT(""),
533 XML_GetCurrentLineNumber(ctx
->parser
));
534 ctx
->node
->AddChild(ctx
->lastAsText
);
537 static void CommentHnd(void *userData
, const char *data
)
539 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
543 // VS: ctx->node == NULL happens if there is a comment before
544 // the root element (e.g. wxDesigner's output). We ignore such
545 // comments, no big deal...
547 new wxXmlNode(wxXML_COMMENT_NODE
,
548 wxT("comment"), CharToString(ctx
->conv
, data
),
549 XML_GetCurrentLineNumber(ctx
->parser
)));
551 ctx
->lastAsText
= NULL
;
554 static void DefaultHnd(void *userData
, const char *s
, int len
)
557 if (len
> 6 && memcmp(s
, "<?xml ", 6) == 0)
559 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
561 wxString buf
= CharToString(ctx
->conv
, s
, (size_t)len
);
563 pos
= buf
.Find(wxT("encoding="));
564 if (pos
!= wxNOT_FOUND
)
565 ctx
->encoding
= buf
.Mid(pos
+ 10).BeforeFirst(buf
[(size_t)pos
+9]);
566 pos
= buf
.Find(wxT("version="));
567 if (pos
!= wxNOT_FOUND
)
568 ctx
->version
= buf
.Mid(pos
+ 9).BeforeFirst(buf
[(size_t)pos
+8]);
572 static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData
),
573 const XML_Char
*name
, XML_Encoding
*info
)
575 // We must build conversion table for expat. The easiest way to do so
576 // is to let wxCSConv convert as string containing all characters to
577 // wide character representation:
585 for (i
= 0; i
< 255; i
++)
587 mbBuf
[0] = (char)(i
+1);
588 if (conv
.MB2WC(wcBuf
, mbBuf
, 2) == (size_t)-1)
590 // invalid/undefined byte in the encoding:
593 info
->map
[i
+1] = (int)wcBuf
[0];
597 info
->convert
= NULL
;
598 info
->release
= NULL
;
605 bool wxXmlDocument::Load(wxInputStream
& stream
, const wxString
& encoding
, int flags
)
610 m_encoding
= encoding
;
613 const size_t BUFSIZE
= 1024;
615 wxXmlParsingContext ctx
;
617 XML_Parser parser
= XML_ParserCreate(NULL
);
619 ctx
.root
= ctx
.node
= NULL
;
620 ctx
.encoding
= wxT("UTF-8"); // default in absence of encoding=""
623 if ( encoding
.CmpNoCase(wxT("UTF-8")) != 0 )
624 ctx
.conv
= new wxCSConv(encoding
);
626 ctx
.removeWhiteOnlyNodes
= (flags
& wxXMLDOC_KEEP_WHITESPACE_NODES
) == 0;
629 XML_SetUserData(parser
, (void*)&ctx
);
630 XML_SetElementHandler(parser
, StartElementHnd
, EndElementHnd
);
631 XML_SetCharacterDataHandler(parser
, TextHnd
);
632 XML_SetStartCdataSectionHandler(parser
, StartCdataHnd
);
633 XML_SetCommentHandler(parser
, CommentHnd
);
634 XML_SetDefaultHandler(parser
, DefaultHnd
);
635 XML_SetUnknownEncodingHandler(parser
, UnknownEncodingHnd
, NULL
);
640 size_t len
= stream
.Read(buf
, BUFSIZE
).LastRead();
641 done
= (len
< BUFSIZE
);
642 if (!XML_Parse(parser
, buf
, len
, done
))
644 wxString
error(XML_ErrorString(XML_GetErrorCode(parser
)),
646 wxLogError(_("XML parsing error: '%s' at line %d"),
648 XML_GetCurrentLineNumber(parser
));
656 if (!ctx
.version
.empty())
657 SetVersion(ctx
.version
);
658 if (!ctx
.encoding
.empty())
659 SetFileEncoding(ctx
.encoding
);
667 XML_ParserFree(parser
);
679 //-----------------------------------------------------------------------------
680 // wxXmlDocument saving routines
681 //-----------------------------------------------------------------------------
683 // write string to output:
684 inline static void OutputString(wxOutputStream
& stream
, const wxString
& str
,
685 wxMBConv
*convMem
= NULL
,
686 wxMBConv
*convFile
= NULL
)
692 wxUnusedVar(convMem
);
694 const wxWX2MBbuf
buf(str
.mb_str(*(convFile
? convFile
: &wxConvUTF8
)));
695 stream
.Write((const char*)buf
, strlen((const char*)buf
));
696 #else // !wxUSE_UNICODE
697 if ( convFile
&& convMem
)
699 wxString
str2(str
.wc_str(*convMem
), *convFile
);
700 stream
.Write(str2
.mb_str(), str2
.Len());
702 else // no conversions to do
704 stream
.Write(str
.mb_str(), str
.Len());
706 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
709 // flags for OutputStringEnt()
712 XML_ESCAPE_QUOTES
= 1
715 // Same as above, but create entities first.
716 // Translates '<' to "<", '>' to ">" and '&' to "&"
717 static void OutputStringEnt(wxOutputStream
& stream
, const wxString
& str
,
718 wxMBConv
*convMem
= NULL
,
719 wxMBConv
*convFile
= NULL
,
728 for (i
= 0; i
< len
; i
++)
731 if (c
== wxT('<') || c
== wxT('>') ||
732 (c
== wxT('&') && str
.Mid(i
+1, 4) != wxT("amp;")) ||
733 ((flags
& XML_ESCAPE_QUOTES
) && c
== wxT('"')))
735 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
739 OutputString(stream
, wxT("<"));
742 OutputString(stream
, wxT(">"));
745 OutputString(stream
, wxT("&"));
748 OutputString(stream
, wxT("""));
756 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
759 inline static void OutputIndentation(wxOutputStream
& stream
, int indent
)
761 wxString str
= wxT("\n");
762 for (int i
= 0; i
< indent
; i
++)
763 str
<< wxT(' ') << wxT(' ');
764 OutputString(stream
, str
);
767 static void OutputNode(wxOutputStream
& stream
, wxXmlNode
*node
, int indent
,
768 wxMBConv
*convMem
, wxMBConv
*convFile
, int indentstep
)
771 wxXmlAttribute
*attr
;
773 switch (node
->GetType())
775 case wxXML_CDATA_SECTION_NODE
:
776 OutputString( stream
, wxT("<![CDATA["));
777 OutputString( stream
, node
->GetContent() );
778 OutputString( stream
, wxT("]]>") );
781 case wxXML_TEXT_NODE
:
782 OutputStringEnt(stream
, node
->GetContent(), convMem
, convFile
);
785 case wxXML_ELEMENT_NODE
:
786 OutputString(stream
, wxT("<"));
787 OutputString(stream
, node
->GetName());
789 attr
= node
->GetAttributes();
792 OutputString(stream
, wxT(" ") + attr
->GetName() + wxT("=\""));
793 OutputStringEnt(stream
, attr
->GetValue(), convMem
, convFile
,
795 OutputString(stream
, wxT("\""));
796 attr
= attr
->GetNext();
799 if (node
->GetChildren())
801 OutputString(stream
, wxT(">"));
803 n
= node
->GetChildren();
806 if (indentstep
>= 0 && n
&& n
->GetType() != wxXML_TEXT_NODE
)
807 OutputIndentation(stream
, indent
+ indentstep
);
808 OutputNode(stream
, n
, indent
+ indentstep
, convMem
, convFile
, indentstep
);
812 if (indentstep
>= 0 && prev
&& prev
->GetType() != wxXML_TEXT_NODE
)
813 OutputIndentation(stream
, indent
);
814 OutputString(stream
, wxT("</"));
815 OutputString(stream
, node
->GetName());
816 OutputString(stream
, wxT(">"));
819 OutputString(stream
, wxT("/>"));
822 case wxXML_COMMENT_NODE
:
823 OutputString(stream
, wxT("<!--"));
824 OutputString(stream
, node
->GetContent(), convMem
, convFile
);
825 OutputString(stream
, wxT("-->"));
829 wxFAIL_MSG(wxT("unsupported node type"));
833 bool wxXmlDocument::Save(wxOutputStream
& stream
, int indentstep
) const
840 wxMBConv
*convMem
= NULL
,
844 convFile
= new wxCSConv(GetFileEncoding());
847 if ( GetFileEncoding().CmpNoCase(GetEncoding()) != 0 )
849 convFile
= new wxCSConv(GetFileEncoding());
850 convMem
= new wxCSConv(GetEncoding());
852 else // file and in-memory encodings are the same, no conversion needed
859 s
.Printf(wxT("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
860 GetVersion().c_str(), GetFileEncoding().c_str());
861 OutputString(stream
, s
);
863 OutputNode(stream
, GetRoot(), 0, convMem
, convFile
, indentstep
);
864 OutputString(stream
, wxT("\n"));