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
)
53 : m_type(type
), m_name(name
), m_content(content
),
54 m_attrs(attrs
), m_parent(parent
),
55 m_children(NULL
), m_next(next
)
59 if (m_parent
->m_children
)
61 m_next
= m_parent
->m_children
;
62 m_parent
->m_children
= this;
65 m_parent
->m_children
= this;
69 wxXmlNode::wxXmlNode(wxXmlNodeType type
, const wxString
& name
,
70 const wxString
& content
)
71 : m_type(type
), m_name(name
), m_content(content
),
72 m_attrs(NULL
), m_parent(NULL
),
73 m_children(NULL
), m_next(NULL
)
76 wxXmlNode::wxXmlNode(const wxXmlNode
& node
)
83 wxXmlNode::~wxXmlNode()
86 for (c
= m_children
; c
; c
= c2
)
92 wxXmlAttribute
*p
, *p2
;
93 for (p
= m_attrs
; p
; p
= p2
)
100 wxXmlNode
& wxXmlNode::operator=(const wxXmlNode
& node
)
103 wxDELETE(m_children
);
108 void wxXmlNode::DoCopy(const wxXmlNode
& node
)
110 m_type
= node
.m_type
;
111 m_name
= node
.m_name
;
112 m_content
= node
.m_content
;
115 wxXmlNode
*n
= node
.m_children
;
118 AddChild(new wxXmlNode(*n
));
123 wxXmlAttribute
*p
= node
.m_attrs
;
126 AddAttribute(p
->GetName(), p
->GetValue());
131 bool wxXmlNode::HasAttribute(const wxString
& attrName
) const
133 wxXmlAttribute
*attr
= GetAttributes();
137 if (attr
->GetName() == attrName
) return true;
138 attr
= attr
->GetNext();
144 bool wxXmlNode::GetAttribute(const wxString
& attrName
, wxString
*value
) const
146 wxXmlAttribute
*attr
= GetAttributes();
150 if (attr
->GetName() == attrName
)
152 *value
= attr
->GetValue();
155 attr
= attr
->GetNext();
161 wxString
wxXmlNode::GetAttribute(const wxString
& attrName
, const wxString
& defaultVal
) const
164 if (GetAttribute(attrName
, &tmp
))
170 void wxXmlNode::AddChild(wxXmlNode
*child
)
172 if (m_children
== NULL
)
176 wxXmlNode
*ch
= m_children
;
177 while (ch
->m_next
) ch
= ch
->m_next
;
180 child
->m_next
= NULL
;
181 child
->m_parent
= this;
184 bool wxXmlNode::InsertChild(wxXmlNode
*child
, wxXmlNode
*before_node
)
186 wxCHECK_MSG(before_node
== NULL
|| before_node
->GetParent() == this, false,
187 wxT("wxXmlNode::InsertChild - the node has incorrect parent"));
188 wxCHECK_MSG(child
, false, wxT("Cannot insert a NULL pointer!"));
190 if (m_children
== before_node
)
192 else if (m_children
== NULL
)
194 if (before_node
!= NULL
)
195 return false; // we have no children so we don't need to search
198 else if (before_node
== NULL
)
201 child
->m_parent
= this;
202 child
->m_next
= m_children
;
208 wxXmlNode
*ch
= m_children
;
209 while (ch
&& ch
->m_next
!= before_node
) ch
= ch
->m_next
;
211 return false; // before_node not found
215 child
->m_parent
= this;
216 child
->m_next
= before_node
;
220 bool wxXmlNode::RemoveChild(wxXmlNode
*child
)
222 if (m_children
== NULL
)
224 else if (m_children
== child
)
226 m_children
= child
->m_next
;
227 child
->m_parent
= NULL
;
228 child
->m_next
= NULL
;
233 wxXmlNode
*ch
= m_children
;
236 if (ch
->m_next
== child
)
238 ch
->m_next
= child
->m_next
;
239 child
->m_parent
= NULL
;
240 child
->m_next
= NULL
;
249 void wxXmlNode::AddProperty(const wxString
& name
, const wxString
& value
)
251 AddProperty(new wxXmlAttribute(name
, value
, NULL
));
254 void wxXmlNode::AddProperty(wxXmlAttribute
*attr
)
260 wxXmlAttribute
*p
= m_attrs
;
261 while (p
->GetNext()) p
= p
->GetNext();
266 bool wxXmlNode::DeleteProperty(const wxString
& name
)
268 wxXmlAttribute
*attr
;
273 else if (m_attrs
->GetName() == name
)
276 m_attrs
= attr
->GetNext();
284 wxXmlAttribute
*p
= m_attrs
;
287 if (p
->GetNext()->GetName() == name
)
290 p
->SetNext(attr
->GetNext());
301 wxString
wxXmlNode::GetNodeContent() const
303 wxXmlNode
*n
= GetChildren();
307 if (n
->GetType() == wxXML_TEXT_NODE
||
308 n
->GetType() == wxXML_CDATA_SECTION_NODE
)
309 return n
->GetContent();
312 return wxEmptyString
;
315 int wxXmlNode::GetDepth(wxXmlNode
*grandparent
) const
317 const wxXmlNode
*n
= this;
324 if (n
== grandparent
)
332 bool wxXmlNode::IsWhitespaceOnly() const
334 return wxIsWhiteOnly(m_content
);
339 //-----------------------------------------------------------------------------
341 //-----------------------------------------------------------------------------
343 wxXmlDocument::wxXmlDocument()
344 : m_version(wxT("1.0")), m_fileEncoding(wxT("utf-8")), m_root(NULL
)
347 m_encoding
= wxT("UTF-8");
351 wxXmlDocument::wxXmlDocument(const wxString
& filename
, const wxString
& encoding
)
352 :wxObject(), m_root(NULL
)
354 if ( !Load(filename
, encoding
) )
360 wxXmlDocument::wxXmlDocument(wxInputStream
& stream
, const wxString
& encoding
)
361 :wxObject(), m_root(NULL
)
363 if ( !Load(stream
, encoding
) )
369 wxXmlDocument::wxXmlDocument(const wxXmlDocument
& doc
)
375 wxXmlDocument
& wxXmlDocument::operator=(const wxXmlDocument
& doc
)
382 void wxXmlDocument::DoCopy(const wxXmlDocument
& doc
)
384 m_version
= doc
.m_version
;
386 m_encoding
= doc
.m_encoding
;
388 m_fileEncoding
= doc
.m_fileEncoding
;
391 m_root
= new wxXmlNode(*doc
.m_root
);
396 bool wxXmlDocument::Load(const wxString
& filename
, const wxString
& encoding
, int flags
)
398 wxFileInputStream
stream(filename
);
401 return Load(stream
, encoding
, flags
);
404 bool wxXmlDocument::Save(const wxString
& filename
, int indentstep
) const
406 wxFileOutputStream
stream(filename
);
409 return Save(stream
, indentstep
);
414 //-----------------------------------------------------------------------------
415 // wxXmlDocument loading routines
416 //-----------------------------------------------------------------------------
418 // converts Expat-produced string in UTF-8 into wxString using the specified
419 // conv or keep in UTF-8 if conv is NULL
420 static wxString
CharToString(wxMBConv
*conv
,
421 const char *s
, size_t len
= wxString::npos
)
426 // there can be no embedded NULs in this string so we don't need the
427 // output length, it will be NUL-terminated
428 const wxWCharBuffer
wbuf(
429 wxConvUTF8
.cMB2WC(s
, len
== wxString::npos
? wxNO_LEN
: len
, NULL
));
431 return wxString(wbuf
, *conv
);
433 // else: the string is wanted in UTF-8
434 #endif // !wxUSE_UNICODE
437 return wxString::FromUTF8(s
, len
);
440 // returns true if the given string contains only whitespaces
441 bool wxIsWhiteOnly(const wxString
& buf
)
443 for ( wxString::const_iterator i
= buf
.begin(); i
!= buf
.end(); ++i
)
446 if ( c
!= wxT(' ') && c
!= wxT('\t') && c
!= wxT('\n') && c
!= wxT('\r'))
453 struct wxXmlParsingContext
458 wxXmlNode
*lastAsText
;
461 bool removeWhiteOnlyNodes
;
465 static void StartElementHnd(void *userData
, const char *name
, const char **atts
)
467 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
468 wxXmlNode
*node
= new wxXmlNode(wxXML_ELEMENT_NODE
, CharToString(ctx
->conv
, name
));
469 const char **a
= atts
;
472 node
->AddAttribute(CharToString(ctx
->conv
, a
[0]), CharToString(ctx
->conv
, a
[1]));
475 if (ctx
->root
== NULL
)
478 ctx
->node
->AddChild(node
);
480 ctx
->lastAsText
= NULL
;
483 static void EndElementHnd(void *userData
, const char* WXUNUSED(name
))
485 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
487 ctx
->node
= ctx
->node
->GetParent();
488 ctx
->lastAsText
= NULL
;
491 static void TextHnd(void *userData
, const char *s
, int len
)
493 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
494 wxString str
= CharToString(ctx
->conv
, s
, len
);
498 ctx
->lastAsText
->SetContent(ctx
->lastAsText
->GetContent() + str
);
502 bool whiteOnly
= false;
503 if (ctx
->removeWhiteOnlyNodes
)
504 whiteOnly
= wxIsWhiteOnly(str
);
508 ctx
->lastAsText
= new wxXmlNode(wxXML_TEXT_NODE
, wxT("text"), str
);
509 ctx
->node
->AddChild(ctx
->lastAsText
);
514 static void StartCdataHnd(void *userData
)
516 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
518 ctx
->lastAsText
= new wxXmlNode(wxXML_CDATA_SECTION_NODE
, wxT("cdata"),wxT(""));
519 ctx
->node
->AddChild(ctx
->lastAsText
);
522 static void CommentHnd(void *userData
, const char *data
)
524 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
528 // VS: ctx->node == NULL happens if there is a comment before
529 // the root element (e.g. wxDesigner's output). We ignore such
530 // comments, no big deal...
531 ctx
->node
->AddChild(new wxXmlNode(wxXML_COMMENT_NODE
,
532 wxT("comment"), CharToString(ctx
->conv
, data
)));
534 ctx
->lastAsText
= NULL
;
537 static void DefaultHnd(void *userData
, const char *s
, int len
)
540 if (len
> 6 && memcmp(s
, "<?xml ", 6) == 0)
542 wxXmlParsingContext
*ctx
= (wxXmlParsingContext
*)userData
;
544 wxString buf
= CharToString(ctx
->conv
, s
, (size_t)len
);
546 pos
= buf
.Find(wxT("encoding="));
547 if (pos
!= wxNOT_FOUND
)
548 ctx
->encoding
= buf
.Mid(pos
+ 10).BeforeFirst(buf
[(size_t)pos
+9]);
549 pos
= buf
.Find(wxT("version="));
550 if (pos
!= wxNOT_FOUND
)
551 ctx
->version
= buf
.Mid(pos
+ 9).BeforeFirst(buf
[(size_t)pos
+8]);
555 static int UnknownEncodingHnd(void * WXUNUSED(encodingHandlerData
),
556 const XML_Char
*name
, XML_Encoding
*info
)
558 // We must build conversion table for expat. The easiest way to do so
559 // is to let wxCSConv convert as string containing all characters to
560 // wide character representation:
568 for (i
= 0; i
< 255; i
++)
570 mbBuf
[0] = (char)(i
+1);
571 if (conv
.MB2WC(wcBuf
, mbBuf
, 2) == (size_t)-1)
573 // invalid/undefined byte in the encoding:
576 info
->map
[i
+1] = (int)wcBuf
[0];
580 info
->convert
= NULL
;
581 info
->release
= NULL
;
588 bool wxXmlDocument::Load(wxInputStream
& stream
, const wxString
& encoding
, int flags
)
593 m_encoding
= encoding
;
596 const size_t BUFSIZE
= 1024;
598 wxXmlParsingContext ctx
;
600 XML_Parser parser
= XML_ParserCreate(NULL
);
602 ctx
.root
= ctx
.node
= NULL
;
603 ctx
.encoding
= wxT("UTF-8"); // default in absence of encoding=""
606 if ( encoding
.CmpNoCase(wxT("UTF-8")) != 0 )
607 ctx
.conv
= new wxCSConv(encoding
);
609 ctx
.removeWhiteOnlyNodes
= (flags
& wxXMLDOC_KEEP_WHITESPACE_NODES
) == 0;
611 XML_SetUserData(parser
, (void*)&ctx
);
612 XML_SetElementHandler(parser
, StartElementHnd
, EndElementHnd
);
613 XML_SetCharacterDataHandler(parser
, TextHnd
);
614 XML_SetStartCdataSectionHandler(parser
, StartCdataHnd
);
615 XML_SetCommentHandler(parser
, CommentHnd
);
616 XML_SetDefaultHandler(parser
, DefaultHnd
);
617 XML_SetUnknownEncodingHandler(parser
, UnknownEncodingHnd
, NULL
);
622 size_t len
= stream
.Read(buf
, BUFSIZE
).LastRead();
623 done
= (len
< BUFSIZE
);
624 if (!XML_Parse(parser
, buf
, len
, done
))
626 wxString
error(XML_ErrorString(XML_GetErrorCode(parser
)),
628 wxLogError(_("XML parsing error: '%s' at line %d"),
630 XML_GetCurrentLineNumber(parser
));
638 if (!ctx
.version
.empty())
639 SetVersion(ctx
.version
);
640 if (!ctx
.encoding
.empty())
641 SetFileEncoding(ctx
.encoding
);
649 XML_ParserFree(parser
);
661 //-----------------------------------------------------------------------------
662 // wxXmlDocument saving routines
663 //-----------------------------------------------------------------------------
665 // write string to output:
666 inline static void OutputString(wxOutputStream
& stream
, const wxString
& str
,
667 wxMBConv
*convMem
= NULL
,
668 wxMBConv
*convFile
= NULL
)
674 wxUnusedVar(convMem
);
676 const wxWX2MBbuf
buf(str
.mb_str(*(convFile
? convFile
: &wxConvUTF8
)));
677 stream
.Write((const char*)buf
, strlen((const char*)buf
));
678 #else // !wxUSE_UNICODE
679 if ( convFile
&& convMem
)
681 wxString
str2(str
.wc_str(*convMem
), *convFile
);
682 stream
.Write(str2
.mb_str(), str2
.Len());
684 else // no conversions to do
686 stream
.Write(str
.mb_str(), str
.Len());
688 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
691 // flags for OutputStringEnt()
694 XML_ESCAPE_QUOTES
= 1
697 // Same as above, but create entities first.
698 // Translates '<' to "<", '>' to ">" and '&' to "&"
699 static void OutputStringEnt(wxOutputStream
& stream
, const wxString
& str
,
700 wxMBConv
*convMem
= NULL
,
701 wxMBConv
*convFile
= NULL
,
710 for (i
= 0; i
< len
; i
++)
713 if (c
== wxT('<') || c
== wxT('>') ||
714 (c
== wxT('&') && str
.Mid(i
+1, 4) != wxT("amp;")) ||
715 ((flags
& XML_ESCAPE_QUOTES
) && c
== wxT('"')))
717 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
721 OutputString(stream
, wxT("<"));
724 OutputString(stream
, wxT(">"));
727 OutputString(stream
, wxT("&"));
730 OutputString(stream
, wxT("""));
738 OutputString(stream
, str
.Mid(last
, i
- last
), convMem
, convFile
);
741 inline static void OutputIndentation(wxOutputStream
& stream
, int indent
)
743 wxString str
= wxT("\n");
744 for (int i
= 0; i
< indent
; i
++)
745 str
<< wxT(' ') << wxT(' ');
746 OutputString(stream
, str
);
749 static void OutputNode(wxOutputStream
& stream
, wxXmlNode
*node
, int indent
,
750 wxMBConv
*convMem
, wxMBConv
*convFile
, int indentstep
)
753 wxXmlAttribute
*attr
;
755 switch (node
->GetType())
757 case wxXML_CDATA_SECTION_NODE
:
758 OutputString( stream
, wxT("<![CDATA["));
759 OutputString( stream
, node
->GetContent() );
760 OutputString( stream
, wxT("]]>") );
763 case wxXML_TEXT_NODE
:
764 OutputStringEnt(stream
, node
->GetContent(), convMem
, convFile
);
767 case wxXML_ELEMENT_NODE
:
768 OutputString(stream
, wxT("<"));
769 OutputString(stream
, node
->GetName());
771 attr
= node
->GetAttributes();
774 OutputString(stream
, wxT(" ") + attr
->GetName() + wxT("=\""));
775 OutputStringEnt(stream
, attr
->GetValue(), convMem
, convFile
,
777 OutputString(stream
, wxT("\""));
778 attr
= attr
->GetNext();
781 if (node
->GetChildren())
783 OutputString(stream
, wxT(">"));
785 n
= node
->GetChildren();
788 if (indentstep
>= 0 && n
&& n
->GetType() != wxXML_TEXT_NODE
)
789 OutputIndentation(stream
, indent
+ indentstep
);
790 OutputNode(stream
, n
, indent
+ indentstep
, convMem
, convFile
, indentstep
);
794 if (indentstep
>= 0 && prev
&& prev
->GetType() != wxXML_TEXT_NODE
)
795 OutputIndentation(stream
, indent
);
796 OutputString(stream
, wxT("</"));
797 OutputString(stream
, node
->GetName());
798 OutputString(stream
, wxT(">"));
801 OutputString(stream
, wxT("/>"));
804 case wxXML_COMMENT_NODE
:
805 OutputString(stream
, wxT("<!--"));
806 OutputString(stream
, node
->GetContent(), convMem
, convFile
);
807 OutputString(stream
, wxT("-->"));
811 wxFAIL_MSG(wxT("unsupported node type"));
815 bool wxXmlDocument::Save(wxOutputStream
& stream
, int indentstep
) const
822 wxMBConv
*convMem
= NULL
,
826 convFile
= new wxCSConv(GetFileEncoding());
829 if ( GetFileEncoding().CmpNoCase(GetEncoding()) != 0 )
831 convFile
= new wxCSConv(GetFileEncoding());
832 convMem
= new wxCSConv(GetEncoding());
834 else // file and in-memory encodings are the same, no conversion needed
841 s
.Printf(wxT("<?xml version=\"%s\" encoding=\"%s\"?>\n"),
842 GetVersion().c_str(), GetFileEncoding().c_str());
843 OutputString(stream
, s
);
845 OutputNode(stream
, GetRoot(), 0, convMem
, convFile
, indentstep
);
846 OutputString(stream
, wxT("\n"));