Search code examples
c++wxwidgets

How to load wxXmlDocument from std::istream?


I would like to load a wxXmlDocument from a std::istream but unfortunately, there's no Load(std::istream&) member function, even if wxWidget is compiled using standard input/output streams.

For what it's worth, I'm using wxWidgets 3.1.0 on macOS.


Solution

  • I don't know if there are alternatives but, since wxXmlDocument provides a Load(wxInputStream&), a solution can be to define an adapter like this one:

    class myStdInputStreamAdapter : public wxInputStream {
    public:
      myStdInputStreamAdapter(std::istream &s): stream{s} {}
    
    protected:
      std::istream &stream;
    
      virtual size_t OnSysRead(void *buffer, size_t bufsize) {
        std::streamsize size = 0;
    
        stream.peek();
    
        if (stream.fail() || stream.bad()) {
          m_lasterror = wxSTREAM_READ_ERROR;
        } else if (stream.eof()) {
          m_lasterror = wxSTREAM_EOF;
        } else {
          size = stream.readsome(static_cast<std::istream::char_type *>(buffer),
                                 bufsize);
        }
    
        return size;
      }
    };
    

    And then use it to load the xml:

    void f(std::istream &istream) {
        wxXmlDocument xml;
    
        myStdInputStreamAdapter inputStreamAdapter(istream);
    
        xml.Load(inputStreamAdapter);
    }