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::AddAttribute(const wxString
& name
, const wxString
& value
)
257 AddProperty(name
, value
);
260 void wxXmlNode::AddAttribute(wxXmlAttribute
*attr
)
265 bool wxXmlNode::DeleteAttribute(const wxString
& name
)
267 return DeleteProperty(name
);
270 void wxXmlNode::AddProperty(const wxString
& name
, const wxString
& value
)
272 AddProperty(new wxXmlAttribute(name
, value
, NULL
));
275 void wxXmlNode::AddProperty(wxXmlAttribute
*attr
)
281 wxXmlAttribute
*p
= m_attrs
;
282 while (p
->GetNext()) p
= p
->GetNext();
287 bool wxXmlNode::DeleteProperty(const wxString
& name
)
289 wxXmlAttribute
*attr
;
294 else if (m_attrs
->GetName() == name
)
297 m_attrs
= attr
->GetNext();
305 wxXmlAttribute
*p
= m_attrs
;
308 if (p
->GetNext()->GetName() == name
)
311 p
->SetNext(attr
->GetNext());
322 wxString
wxXmlNode::GetNodeContent() const
324 wxXmlNode
*n
= GetChildren();
328 if (n
->GetType() == wxXML_TEXT_NODE
||
329 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
330 return n
->GetContent();
333 return wxEmptyString
;
336 int wxXmlNode::GetDepth(wxXmlNode
*grandparent
) const
338 const wxXmlNode
*n
= this;
345 if (n
== grandparent
)
353 bool wxXmlNode::IsWhitespaceOnly() const
355 return wxIsWhiteOnly(m_content
);
360 //-----------------------------------------------------------------------------
362 //-----------------------------------------------------------------------------
364 wxXmlDocument::wxXmlDocument()
365 : m_version(wxT("1.0")), m_fileEncoding(wxT("utf-8")), m_root(NULL
)
368 m_encoding
= wxT("UTF-8");
372 wxXmlDocument::wxXmlDocument(const wxString
& filename
, const wxString
& encoding
)
373 :wxObject(), m_root(NULL
)
375 if ( !Load(filename
, encoding
) )
381 wxXmlDocument::wxXmlDocument(wxInputStream
& stream
, const wxString
& encoding
)
382 :wxObject(), m_root(NULL
)
384 if ( !Load(stream
, encoding
) )
390 wxXmlDocument::wxXmlDocument(const wxXmlDocument
& doc
)
396 wxXmlDocument
& wxXmlDocument::operator=(const wxXmlDocument
& doc
)
403 void wxXmlDocument::DoCopy(const wxXmlDocument
& doc
)
405 m_version
= doc
.m_version
;
407 m_encoding
= doc
.m_encoding
;
409 m_fileEncoding
= doc
.m_fileEncoding
;
412 m_root
= new wxXmlNode(*doc
.m_root
);
417 bool wxXmlDocument::Load(const wxString
& filename
, const wxString
& encoding
, int flags
)
419 wxFileInputStream
stream(filename
);
422 return Load(stream
, encoding
, flags
);
425 bool wxXmlDocument::Save(const wxString
& filename
, int indentstep
) const
427 wxFileOutputStream
stream(filename
);
430 return Save(stream
, indentstep
);
435 //-----------------------------------------------------------------------------
436 // wxXmlDocument loading routines
437 //-----------------------------------------------------------------------------
439 // converts Expat-produced string in UTF-8 into wxString using the specified
440 // conv or keep in UTF-8 if conv is NULL
441 static wxString
CharToString(wxMBConv
*conv
,
442 const char *s
, size_t len
= wxString::npos
)
447 // there can be no embedded NULs in this string so we don't need the
448 // output length, it will be NUL-terminated
449 const wxWCharBuffer
wbuf(
450 wxConvUTF8
.cMB2WC(s
, len
== wxString::npos
? wxNO_LEN
: len
, NULL
));
452 return wxString(wbuf
, *conv
);
454 // else: the string is wanted in UTF-8
455 #endif // !wxUSE_UNICODE
458 return wxString::FromUTF8(s
, len
);
461 // returns true if the given string contains only whitespaces
462 bool wxIsWhiteOnly(const wxString
& buf
)
464 for ( wxString::const_iterator i
= buf
.begin(); i
!= buf
.end(); ++i
)
467 if ( c
!= wxT(' ') && c
!= wxT('\t') && c
!= wxT('\n') && c
!= wxT('\r'))
474 struct wxXmlParsingContext
480 wxXmlNode
*lastAsText
;
483 bool removeWhiteOnlyNodes
;
487 static void StartElementHnd(void *userData
, const char *name
, const char **atts
)
489 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
490 wxXmlNode
*node
= new wxXmlNode(wxXML_ELEMENT_NODE
,
491 CharToString(ctx
->conv
, name
),
493 XML_GetCurrentLineNumber(ctx
->parser
));
494 const char **a
= atts
;
498 node
->AddAttribute(CharToString(ctx
->conv
, a
[0]), CharToString(ctx
->conv
, a
[1]));
501 if (ctx
->root
== NULL
)
504 ctx
->node
->AddChild(node
);
506 ctx
->lastAsText
= NULL
;
509 static void EndElementHnd(void *userData
, const char* WXUNUSED(name
))
511 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
513 ctx
->node
= ctx
->node
->GetParent();
514 ctx
->lastAsText
= NULL
;
517 static void TextHnd(void *userData
, const char *s
, int len
)
519 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
520 wxString str
= CharToString(ctx
->conv
, s
, len
);
524 ctx
->lastAsText
->SetContent(ctx
->lastAsText
->GetContent() + str
);
528 bool whiteOnly
= false;
529 if (ctx
->removeWhiteOnlyNodes
)
530 whiteOnly
= wxIsWhiteOnly(str
);
535 new wxXmlNode(wxXML_TEXT_NODE
, wxT("text"), str
,
536 XML_GetCurrentLineNumber(ctx
->parser
));
537 ctx
->node
->AddChild(ctx
->lastAsText
);
542 static void StartCdataHnd(void *userData
)
544 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
547 new wxXmlNode(wxXML_CDATA_SECTION_NODE
, wxT("cdata"), wxT(""),
548 XML_GetCurrentLineNumber(ctx
->parser
));
549 ctx
->node
->AddChild(ctx
->lastAsText
);
552 static void CommentHnd(void *userData
, const char *data
)
554 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
558 // VS: ctx->node == NULL happens if there is a comment before
559 // the root element (e.g. wxDesigner's output). We ignore such
560 // comments, no big deal...
562 new wxXmlNode(wxXML_COMMENT_NODE
,
563 wxT("comment"), CharToString(ctx
->conv
, data
),
564 XML_GetCurrentLineNumber(ctx
->parser
)));
566 ctx
->lastAsText
= NULL
;
569 static void DefaultHnd(void *userData
, const char *s
, int len
)
572 if (len
> 6 && memcmp(s
, "<?xml ", 6) == 0)
574 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
576 wxString buf
= CharToString(ctx
->conv
, s
, (size_t)len
);
578 pos
= buf
.Find(wxT("encoding="));
579 if (pos
!= wxNOT_FOUND
)
580 ctx
->encoding
= buf
.Mid(pos
+ 10).BeforeFirst(buf
[(size_t)pos
+9]);
581 pos
= buf
.Find(wxT("version="));
582 if (pos
!= wxNOT_FOUND
)
583 ctx
->version
= buf
.Mid(pos
+ 9).BeforeFirst(buf
[(size_t)pos
+8]);
587 static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData
),
588 const XML_Char
*name
, XML_Encoding
*info
)
590 // We must build conversion table for expat. The easiest way to do so
591 // is to let wxCSConv convert as string containing all characters to
592 // wide character representation:
600 for (i
= 0; i
< 255; i
++)
602 mbBuf
[0] = (char)(i
+1);
603 if (conv
.MB2WC(wcBuf
, mbBuf
, 2) == (size_t)-1)
605 // invalid/undefined byte in the encoding:
608 info
->map
[i
+1] = (int)wcBuf
[0];
612 info
->convert
= NULL
;
613 info
->release
= NULL
;
620 bool wxXmlDocument::Load(wxInputStream
& stream
, const wxString
& encoding
, int flags
)
625 m_encoding
= encoding
;
628 const size_t BUFSIZE
= 1024;
630 wxXmlParsingContext ctx
;
632 XML_Parser parser
= XML_ParserCreate(NULL
);
634 ctx
.root
= ctx
.node
= NULL
;
635 ctx
.encoding
= wxT("UTF-8"); // default in absence of encoding=""
638 if ( encoding
.CmpNoCase(wxT("UTF-8")) != 0 )
639 ctx
.conv
= new wxCSConv(encoding
);
641 ctx
.removeWhiteOnlyNodes
= (flags
& wxXMLDOC_KEEP_WHITESPACE_NODES
) == 0;
644 XML_SetUserData(parser
, (void*)&ctx
);
645 XML_SetElementHandler(parser
, StartElementHnd
, EndElementHnd
);
646 XML_SetCharacterDataHandler(parser
, TextHnd
);
647 XML_SetStartCdataSectionHandler(parser
, StartCdataHnd
);
648 XML_SetCommentHandler(parser
, CommentHnd
);
649 XML_SetDefaultHandler(parser
, DefaultHnd
);
650 XML_SetUnknownEncodingHandler(parser
, UnknownEncodingHnd
, NULL
);
655 size_t len
= stream
.Read(buf
, BUFSIZE
).LastRead();
656 done
= (len
< BUFSIZE
);
657 if (!XML_Parse(parser
, buf
, len
, done
))
659 wxString
error(XML_ErrorString(XML_GetErrorCode(parser
)),
661 wxLogError(_("XML parsing error: '%s' at line %d"),
663 XML_GetCurrentLineNumber(parser
));
671 if (!ctx
.version
.empty())
672 SetVersion(ctx
.version
);
673 if (!ctx
.encoding
.empty())
674 SetFileEncoding(ctx
.encoding
);
682 XML_ParserFree(parser
);
694 //-----------------------------------------------------------------------------
695 // wxXmlDocument saving routines
696 //-----------------------------------------------------------------------------
698 // write string to output:
699 inline static void OutputString(wxOutputStream
& stream
, const wxString
& str
,
700 wxMBConv
*convMem
= NULL
,
701 wxMBConv
*convFile
= NULL
)
707 wxUnusedVar(convMem
);
709 const wxWX2MBbuf
buf(str
.mb_str(*(convFile
? convFile
: &wxConvUTF8
)));
710 stream
.Write((const char*)buf
, strlen((const char*)buf
));
711 #else // !wxUSE_UNICODE
712 if ( convFile
&& convMem
)
714 wxString
str2(str
.wc_str(*convMem
), *convFile
);
715 stream
.Write(str2
.mb_str(), str2
.Len());
717 else // no conversions to do
719 stream
.Write(str
.mb_str(), str
.Len());
721 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
724 // flags for OutputStringEnt()
727 XML_ESCAPE_QUOTES
= 1
730 // Same as above, but create entities first.
731 // Translates '<' to "<", '>' to ">" and '&' to "&"
732 static void OutputStringEnt(wxOutputStream
& stream
, const wxString
& str
,
733 wxMBConv
*convMem
= NULL
,
734 wxMBConv
*convFile
= NULL
,
743 for (i
= 0; i
< len
; i
++)
746 if (c
== wxT('<') || c
== wxT('>') ||
747 (c
== wxT('&') && str
.Mid(i
+1, 4) != wxT("amp;")) ||
748 ((flags
& XML_ESCAPE_QUOTES
) && c
== wxT('"')))
750 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
754 OutputString(stream
, wxT("<"));
757 OutputString(stream
, wxT(">"));
760 OutputString(stream
, wxT("&"));
763 OutputString(stream
, wxT("""));
771 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
774 inline static void OutputIndentation(wxOutputStream
& stream
, int indent
)
776 wxString str
= wxT("\n");
777 for (int i
= 0; i
< indent
; i
++)
778 str
<< wxT(' ') << wxT(' ');
779 OutputString(stream
, str
);
782 static void OutputNode(wxOutputStream
& stream
, wxXmlNode
*node
, int indent
,
783 wxMBConv
*convMem
, wxMBConv
*convFile
, int indentstep
)
786 wxXmlAttribute
*attr
;
788 switch (node
->GetType())
790 case wxXML_CDATA_SECTION_NODE
:
791 OutputString( stream
, wxT("<![CDATA["));
792 OutputString( stream
, node
->GetContent() );
793 OutputString( stream
, wxT("]]>") );
796 case wxXML_TEXT_NODE
:
797 OutputStringEnt(stream
, node
->GetContent(), convMem
, convFile
);
800 case wxXML_ELEMENT_NODE
:
801 OutputString(stream
, wxT("<"));
802 OutputString(stream
, node
->GetName());
804 attr
= node
->GetAttributes();
807 OutputString(stream
, wxT(" ") + attr
->GetName() + wxT("=\""));
808 OutputStringEnt(stream
, attr
->GetValue(), convMem
, convFile
,
810 OutputString(stream
, wxT("\""));
811 attr
= attr
->GetNext();
814 if (node
->GetChildren())
816 OutputString(stream
, wxT(">"));
818 n
= node
->GetChildren();
821 if (indentstep
>= 0 && n
&& n
->GetType() != wxXML_TEXT_NODE
)
822 OutputIndentation(stream
, indent
+ indentstep
);
823 OutputNode(stream
, n
, indent
+ indentstep
, convMem
, convFile
, indentstep
);
827 if (indentstep
>= 0 && prev
&& prev
->GetType() != wxXML_TEXT_NODE
)
828 OutputIndentation(stream
, indent
);
829 OutputString(stream
, wxT("</"));
830 OutputString(stream
, node
->GetName());
831 OutputString(stream
, wxT(">"));
834 OutputString(stream
, wxT("/>"));
837 case wxXML_COMMENT_NODE
:
838 OutputString(stream
, wxT("<!--"));
839 OutputString(stream
, node
->GetContent(), convMem
, convFile
);
840 OutputString(stream
, wxT("-->"));
844 wxFAIL_MSG(wxT("unsupported node type"));
848 bool wxXmlDocument::Save(wxOutputStream
& stream
, int indentstep
) const
855 wxMBConv
*convMem
= NULL
,
859 convFile
= new wxCSConv(GetFileEncoding());
862 if ( GetFileEncoding().CmpNoCase(GetEncoding()) != 0 )
864 convFile
= new wxCSConv(GetFileEncoding());
865 convMem
= new wxCSConv(GetEncoding());
867 else // file and in-memory encodings are the same, no conversion needed
874 s
.Printf(wxT("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
875 GetVersion().c_str(), GetFileEncoding().c_str());
876 OutputString(stream
, s
);
878 OutputNode(stream
, GetRoot(), 0, convMem
, convFile
, indentstep
);
879 OutputString(stream
, wxT("\n"));