c++xmlxsdxml-parsingcodesynthesis

Code Synthesis XSD parsing/data binding xml string instead of xml file


I have seen tutorials all over the place for explaining how to get Code Synthesis xsd to work if you provide the xml in a file on your system, but I have not been able to find anything about providing the xml as a string.

I am receiving the xml from a TCP connection and I am attempting to parse it with Code Synthesis xsd, and it just seems like a useless additional step to create an xml file when I already have it in memory as a string.

And yes, this is in C++.


Solution

  • You can use std::istringstream to make a string appear as std::istream and then parse that:

    #include <sstream>
    
    std::string str = ... // Input XML in a string.
    std::istringstream istr (str);
    
    std::auto_ptr<root_type> r = root (istr);
    

    Here root_type is the type and root is the name of the root element of your XML. The same approach works for serialization except you use std::ostringstream:

    #include <sstream>
    
    std::ostringstream ostr;
    
    root (ostr, *r, ...);
    std::string str = ostr.str () // Output XML in a string.