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 // inserts a new node in front of 'followingNode'
191 bool wxXmlNode::InsertChild(wxXmlNode
*child
, wxXmlNode
*followingNode
)
193 wxCHECK_MSG( child
, false, "cannot insert a NULL node!" );
194 wxCHECK_MSG( child
->m_parent
== NULL
, false, "node already has a parent" );
195 wxCHECK_MSG( child
->m_next
== NULL
, false, "node already has m_next" );
196 wxCHECK_MSG( followingNode
== NULL
|| followingNode
->GetParent() == this,
198 "wxXmlNode::InsertChild - followingNode has incorrect parent" );
200 // this is for backward compatibility, NULL was allowed here thanks to
201 // the confusion about followingNode's meaning
202 if ( followingNode
== NULL
)
203 followingNode
= m_children
;
205 if ( m_children
== followingNode
)
207 child
->m_next
= m_children
;
212 wxXmlNode
*ch
= m_children
;
213 while ( ch
&& ch
->m_next
!= followingNode
)
217 wxFAIL_MSG( "followingNode has this node as parent, but couldn't be found among children" );
221 child
->m_next
= followingNode
;
225 child
->m_parent
= this;
229 bool wxXmlNode::RemoveChild(wxXmlNode
*child
)
231 if (m_children
== NULL
)
233 else if (m_children
== child
)
235 m_children
= child
->m_next
;
236 child
->m_parent
= NULL
;
237 child
->m_next
= NULL
;
242 wxXmlNode
*ch
= m_children
;
245 if (ch
->m_next
== child
)
247 ch
->m_next
= child
->m_next
;
248 child
->m_parent
= NULL
;
249 child
->m_next
= NULL
;
258 void wxXmlNode::AddAttribute(const wxString
& name
, const wxString
& value
)
260 AddProperty(name
, value
);
263 void wxXmlNode::AddAttribute(wxXmlAttribute
*attr
)
268 bool wxXmlNode::DeleteAttribute(const wxString
& name
)
270 return DeleteProperty(name
);
273 void wxXmlNode::AddProperty(const wxString
& name
, const wxString
& value
)
275 AddProperty(new wxXmlAttribute(name
, value
, NULL
));
278 void wxXmlNode::AddProperty(wxXmlAttribute
*attr
)
284 wxXmlAttribute
*p
= m_attrs
;
285 while (p
->GetNext()) p
= p
->GetNext();
290 bool wxXmlNode::DeleteProperty(const wxString
& name
)
292 wxXmlAttribute
*attr
;
297 else if (m_attrs
->GetName() == name
)
300 m_attrs
= attr
->GetNext();
308 wxXmlAttribute
*p
= m_attrs
;
311 if (p
->GetNext()->GetName() == name
)
314 p
->SetNext(attr
->GetNext());
325 wxString
wxXmlNode::GetNodeContent() const
327 wxXmlNode
*n
= GetChildren();
331 if (n
->GetType() == wxXML_TEXT_NODE
||
332 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
333 return n
->GetContent();
336 return wxEmptyString
;
339 int wxXmlNode::GetDepth(wxXmlNode
*grandparent
) const
341 const wxXmlNode
*n
= this;
348 if (n
== grandparent
)
356 bool wxXmlNode::IsWhitespaceOnly() const
358 return wxIsWhiteOnly(m_content
);
363 //-----------------------------------------------------------------------------
365 //-----------------------------------------------------------------------------
367 wxXmlDocument::wxXmlDocument()
368 : m_version(wxT("1.0")), m_fileEncoding(wxT("utf-8")), m_root(NULL
)
371 m_encoding
= wxT("UTF-8");
375 wxXmlDocument::wxXmlDocument(const wxString
& filename
, const wxString
& encoding
)
376 :wxObject(), m_root(NULL
)
378 if ( !Load(filename
, encoding
) )
384 wxXmlDocument::wxXmlDocument(wxInputStream
& stream
, const wxString
& encoding
)
385 :wxObject(), m_root(NULL
)
387 if ( !Load(stream
, encoding
) )
393 wxXmlDocument::wxXmlDocument(const wxXmlDocument
& doc
)
399 wxXmlDocument
& wxXmlDocument::operator=(const wxXmlDocument
& doc
)
406 void wxXmlDocument::DoCopy(const wxXmlDocument
& doc
)
408 m_version
= doc
.m_version
;
410 m_encoding
= doc
.m_encoding
;
412 m_fileEncoding
= doc
.m_fileEncoding
;
415 m_root
= new wxXmlNode(*doc
.m_root
);
420 bool wxXmlDocument::Load(const wxString
& filename
, const wxString
& encoding
, int flags
)
422 wxFileInputStream
stream(filename
);
425 return Load(stream
, encoding
, flags
);
428 bool wxXmlDocument::Save(const wxString
& filename
, int indentstep
) const
430 wxFileOutputStream
stream(filename
);
433 return Save(stream
, indentstep
);
438 //-----------------------------------------------------------------------------
439 // wxXmlDocument loading routines
440 //-----------------------------------------------------------------------------
442 // converts Expat-produced string in UTF-8 into wxString using the specified
443 // conv or keep in UTF-8 if conv is NULL
444 static wxString
CharToString(wxMBConv
*conv
,
445 const char *s
, size_t len
= wxString::npos
)
450 // there can be no embedded NULs in this string so we don't need the
451 // output length, it will be NUL-terminated
452 const wxWCharBuffer
wbuf(
453 wxConvUTF8
.cMB2WC(s
, len
== wxString::npos
? wxNO_LEN
: len
, NULL
));
455 return wxString(wbuf
, *conv
);
457 // else: the string is wanted in UTF-8
458 #endif // !wxUSE_UNICODE
461 return wxString::FromUTF8(s
, len
);
464 // returns true if the given string contains only whitespaces
465 bool wxIsWhiteOnly(const wxString
& buf
)
467 for ( wxString::const_iterator i
= buf
.begin(); i
!= buf
.end(); ++i
)
470 if ( c
!= wxT(' ') && c
!= wxT('\t') && c
!= wxT('\n') && c
!= wxT('\r'))
477 struct wxXmlParsingContext
483 wxXmlNode
*lastAsText
;
486 bool removeWhiteOnlyNodes
;
490 static void StartElementHnd(void *userData
, const char *name
, const char **atts
)
492 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
493 wxXmlNode
*node
= new wxXmlNode(wxXML_ELEMENT_NODE
,
494 CharToString(ctx
->conv
, name
),
496 XML_GetCurrentLineNumber(ctx
->parser
));
497 const char **a
= atts
;
501 node
->AddAttribute(CharToString(ctx
->conv
, a
[0]), CharToString(ctx
->conv
, a
[1]));
504 if (ctx
->root
== NULL
)
507 ctx
->node
->AddChild(node
);
509 ctx
->lastAsText
= NULL
;
512 static void EndElementHnd(void *userData
, const char* WXUNUSED(name
))
514 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
516 ctx
->node
= ctx
->node
->GetParent();
517 ctx
->lastAsText
= NULL
;
520 static void TextHnd(void *userData
, const char *s
, int len
)
522 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
523 wxString str
= CharToString(ctx
->conv
, s
, len
);
527 ctx
->lastAsText
->SetContent(ctx
->lastAsText
->GetContent() + str
);
531 bool whiteOnly
= false;
532 if (ctx
->removeWhiteOnlyNodes
)
533 whiteOnly
= wxIsWhiteOnly(str
);
538 new wxXmlNode(wxXML_TEXT_NODE
, wxT("text"), str
,
539 XML_GetCurrentLineNumber(ctx
->parser
));
540 ctx
->node
->AddChild(ctx
->lastAsText
);
545 static void StartCdataHnd(void *userData
)
547 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
550 new wxXmlNode(wxXML_CDATA_SECTION_NODE
, wxT("cdata"), wxT(""),
551 XML_GetCurrentLineNumber(ctx
->parser
));
552 ctx
->node
->AddChild(ctx
->lastAsText
);
555 static void CommentHnd(void *userData
, const char *data
)
557 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
561 // VS: ctx->node == NULL happens if there is a comment before
562 // the root element (e.g. wxDesigner's output). We ignore such
563 // comments, no big deal...
565 new wxXmlNode(wxXML_COMMENT_NODE
,
566 wxT("comment"), CharToString(ctx
->conv
, data
),
567 XML_GetCurrentLineNumber(ctx
->parser
)));
569 ctx
->lastAsText
= NULL
;
572 static void DefaultHnd(void *userData
, const char *s
, int len
)
575 if (len
> 6 && memcmp(s
, "<?xml ", 6) == 0)
577 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
579 wxString buf
= CharToString(ctx
->conv
, s
, (size_t)len
);
581 pos
= buf
.Find(wxT("encoding="));
582 if (pos
!= wxNOT_FOUND
)
583 ctx
->encoding
= buf
.Mid(pos
+ 10).BeforeFirst(buf
[(size_t)pos
+9]);
584 pos
= buf
.Find(wxT("version="));
585 if (pos
!= wxNOT_FOUND
)
586 ctx
->version
= buf
.Mid(pos
+ 9).BeforeFirst(buf
[(size_t)pos
+8]);
590 static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData
),
591 const XML_Char
*name
, XML_Encoding
*info
)
593 // We must build conversion table for expat. The easiest way to do so
594 // is to let wxCSConv convert as string containing all characters to
595 // wide character representation:
603 for (i
= 0; i
< 255; i
++)
605 mbBuf
[0] = (char)(i
+1);
606 if (conv
.MB2WC(wcBuf
, mbBuf
, 2) == (size_t)-1)
608 // invalid/undefined byte in the encoding:
611 info
->map
[i
+1] = (int)wcBuf
[0];
615 info
->convert
= NULL
;
616 info
->release
= NULL
;
623 bool wxXmlDocument::Load(wxInputStream
& stream
, const wxString
& encoding
, int flags
)
628 m_encoding
= encoding
;
631 const size_t BUFSIZE
= 1024;
633 wxXmlParsingContext ctx
;
635 XML_Parser parser
= XML_ParserCreate(NULL
);
637 ctx
.root
= ctx
.node
= NULL
;
638 ctx
.encoding
= wxT("UTF-8"); // default in absence of encoding=""
641 if ( encoding
.CmpNoCase(wxT("UTF-8")) != 0 )
642 ctx
.conv
= new wxCSConv(encoding
);
644 ctx
.removeWhiteOnlyNodes
= (flags
& wxXMLDOC_KEEP_WHITESPACE_NODES
) == 0;
647 XML_SetUserData(parser
, (void*)&ctx
);
648 XML_SetElementHandler(parser
, StartElementHnd
, EndElementHnd
);
649 XML_SetCharacterDataHandler(parser
, TextHnd
);
650 XML_SetStartCdataSectionHandler(parser
, StartCdataHnd
);
651 XML_SetCommentHandler(parser
, CommentHnd
);
652 XML_SetDefaultHandler(parser
, DefaultHnd
);
653 XML_SetUnknownEncodingHandler(parser
, UnknownEncodingHnd
, NULL
);
658 size_t len
= stream
.Read(buf
, BUFSIZE
).LastRead();
659 done
= (len
< BUFSIZE
);
660 if (!XML_Parse(parser
, buf
, len
, done
))
662 wxString
error(XML_ErrorString(XML_GetErrorCode(parser
)),
664 wxLogError(_("XML parsing error: '%s' at line %d"),
666 XML_GetCurrentLineNumber(parser
));
674 if (!ctx
.version
.empty())
675 SetVersion(ctx
.version
);
676 if (!ctx
.encoding
.empty())
677 SetFileEncoding(ctx
.encoding
);
685 XML_ParserFree(parser
);
697 //-----------------------------------------------------------------------------
698 // wxXmlDocument saving routines
699 //-----------------------------------------------------------------------------
701 // write string to output:
702 inline static void OutputString(wxOutputStream
& stream
, const wxString
& str
,
703 wxMBConv
*convMem
= NULL
,
704 wxMBConv
*convFile
= NULL
)
710 wxUnusedVar(convMem
);
712 const wxWX2MBbuf
buf(str
.mb_str(*(convFile
? convFile
: &wxConvUTF8
)));
713 stream
.Write((const char*)buf
, strlen((const char*)buf
));
714 #else // !wxUSE_UNICODE
715 if ( convFile
&& convMem
)
717 wxString
str2(str
.wc_str(*convMem
), *convFile
);
718 stream
.Write(str2
.mb_str(), str2
.Len());
720 else // no conversions to do
722 stream
.Write(str
.mb_str(), str
.Len());
724 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
727 // flags for OutputStringEnt()
730 XML_ESCAPE_QUOTES
= 1
733 // Same as above, but create entities first.
734 // Translates '<' to "<", '>' to ">" and '&' to "&"
735 static void OutputStringEnt(wxOutputStream
& stream
, const wxString
& str
,
736 wxMBConv
*convMem
= NULL
,
737 wxMBConv
*convFile
= NULL
,
746 for (i
= 0; i
< len
; i
++)
749 if (c
== wxT('<') || c
== wxT('>') ||
750 (c
== wxT('&') && str
.Mid(i
+1, 4) != wxT("amp;")) ||
751 ((flags
& XML_ESCAPE_QUOTES
) && c
== wxT('"')))
753 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
757 OutputString(stream
, wxT("<"));
760 OutputString(stream
, wxT(">"));
763 OutputString(stream
, wxT("&"));
766 OutputString(stream
, wxT("""));
774 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
777 inline static void OutputIndentation(wxOutputStream
& stream
, int indent
)
779 wxString str
= wxT("\n");
780 for (int i
= 0; i
< indent
; i
++)
781 str
<< wxT(' ') << wxT(' ');
782 OutputString(stream
, str
);
785 static void OutputNode(wxOutputStream
& stream
, wxXmlNode
*node
, int indent
,
786 wxMBConv
*convMem
, wxMBConv
*convFile
, int indentstep
)
789 wxXmlAttribute
*attr
;
791 switch (node
->GetType())
793 case wxXML_CDATA_SECTION_NODE
:
794 OutputString( stream
, wxT("<![CDATA["));
795 OutputString( stream
, node
->GetContent() );
796 OutputString( stream
, wxT("]]>") );
799 case wxXML_TEXT_NODE
:
800 OutputStringEnt(stream
, node
->GetContent(), convMem
, convFile
);
803 case wxXML_ELEMENT_NODE
:
804 OutputString(stream
, wxT("<"));
805 OutputString(stream
, node
->GetName());
807 attr
= node
->GetAttributes();
810 OutputString(stream
, wxT(" ") + attr
->GetName() + wxT("=\""));
811 OutputStringEnt(stream
, attr
->GetValue(), convMem
, convFile
,
813 OutputString(stream
, wxT("\""));
814 attr
= attr
->GetNext();
817 if (node
->GetChildren())
819 OutputString(stream
, wxT(">"));
821 n
= node
->GetChildren();
824 if (indentstep
>= 0 && n
&& n
->GetType() != wxXML_TEXT_NODE
)
825 OutputIndentation(stream
, indent
+ indentstep
);
826 OutputNode(stream
, n
, indent
+ indentstep
, convMem
, convFile
, indentstep
);
830 if (indentstep
>= 0 && prev
&& prev
->GetType() != wxXML_TEXT_NODE
)
831 OutputIndentation(stream
, indent
);
832 OutputString(stream
, wxT("</"));
833 OutputString(stream
, node
->GetName());
834 OutputString(stream
, wxT(">"));
837 OutputString(stream
, wxT("/>"));
840 case wxXML_COMMENT_NODE
:
841 OutputString(stream
, wxT("<!--"));
842 OutputString(stream
, node
->GetContent(), convMem
, convFile
);
843 OutputString(stream
, wxT("-->"));
847 wxFAIL_MSG(wxT("unsupported node type"));
851 bool wxXmlDocument::Save(wxOutputStream
& stream
, int indentstep
) const
858 wxMBConv
*convMem
= NULL
,
862 convFile
= new wxCSConv(GetFileEncoding());
865 if ( GetFileEncoding().CmpNoCase(GetEncoding()) != 0 )
867 convFile
= new wxCSConv(GetFileEncoding());
868 convMem
= new wxCSConv(GetEncoding());
870 else // file and in-memory encodings are the same, no conversion needed
877 s
.Printf(wxT("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
878 GetVersion().c_str(), GetFileEncoding().c_str());
879 OutputString(stream
, s
);
881 OutputNode(stream
, GetRoot(), 0, convMem
, convFile
, indentstep
);
882 OutputString(stream
, wxT("\n"));