Bryan wrote:
If I have the following string from a huge xml file:
std::string s = "<input key1=\"v1\" key2=\"val4\" key3=\"test\" />";
I need to get the values associated with the keys out from this line.
What is the best way to do this? I was looking at sscanf, and
std::string find, but this seems kind of brute force to find the key,
get the pos, increment by 2 (for the = and first ") then grab everything
up to the next ". But maybe this is the best approach?
Is there a pretty way to have a small function that does this:
void GetValFromKey(std::string& input, std::string& key, std::string&
value)
{
std::string val;
// find val from key
value = val;
}
I'm thinking that parsing by value is not viable. You're probably
better off collecting the values in a container. The changing length of
each value as well as the number of values present should not cause the
function to fail.
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <iterator>
template< typename S >
void parsekeys( const S& r_s, std::vector< S >& r_v)
{
typename S::size_type left(0), right(0);
while( r_s.npos (left = r_s.find_first_of('\"', right + 1)) )
{
right = r_s.find_first_of('\"', ++left);
r_v.push_back( S(r_s, left, right - left) );
}
}
int main()
{
std::string s = "<input key1=\"v1\" key2=\"val4\" key3=\"test\" />";
std::vector<std::stringvs;
parsekeys(s, vs);
std::copy( vs.begin(),
vs.end(),
std::ostream_iterator<std::string>( std::cout, "\n"
) );
return 0;
}
Another option is to load the keys and their corresponding values in a
std::map.
Have you considered Xerces?
http://xml.apache.org/
ot TinyXML?
http://www.grinninglizard.com/tinyxml/