How to load XML document from `std::istream`?

﹥>﹥吖頭↗ 提交于 2019-12-11 13:40:02

问题


I'd like to load TinyXml documents from std::istream, but it doesn't contain such method:

/** Load a file using the current document value.
    Returns true if successful. Will delete any existing
    document data before loading.
*/
bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the current document value. Returns true if successful.
bool SaveFile() const;
/// Load a file using the given filename. Returns true if successful.
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given filename. Returns true if successful.
bool SaveFile( const char * filename ) const;
/** Load a file using the given FILE*. Returns true if successful. Note that this method
    doesn't stream - the entire object pointed at by the FILE*
    will be interpreted as an XML file. TinyXML doesn't stream in XML from the current
    file location. Streaming may be added in the future.
*/
bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );

I see that it contains function that uses FILE, is it possible to convert std::istream to FILE?


回答1:


Load the entire data from the istream and then use TiXmlDocument::Parse.




回答2:


I've found clear solution here:

C++ style input:

  • based on std::istream
  • operator>>

Reads XML from a stream, making it useful for network transmission. The tricky part is knowing when the XML document is complete, since there will almost certainly be other data in the stream. TinyXML will assume the XML data is complete after it reads the root element. Put another way, documents that are ill-constructed with more than one root element will not read correctly. Also note that operator>> is somewhat slower than Parse, due to both implementation of the STL and limitations of TinyXML.

Example:

std::istream *in = ResourceManager::getInstance().getResource(resourceName);
if(in) {
   TiXmlDocument doc;
   // load document from resource stream
   *in >> doc;
}


来源:https://stackoverflow.com/questions/12338476/how-to-load-xml-document-from-stdistream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!