Re: [xml] Problems with xmlChar* as a key in STL Map

Here is the problem, by default the STL libraries use the operator== method
for any given comparison.

So if you try to use a map like this:

map<xmlChar *, my_object> my_map;

it will compare the pointers themselves, and not the contents of the
Its like saying:

xmlChar  *a, *b;
if( a==b ) {
    // do something

The previous code is not valid when normally operating on strings.

The workaround is to provide a comparator function to the map object, you
can use the following:

struct xmlCmp {
    bool operator()(const xmlChar* s1, const xmlChar* s2) const {
        return xmlStrcmp(s1, s2) < 0;
map<xmlChar *, my_object, xmlCmp> my_better_map;

That should solve your STL problems.


James Wert Jr.
JWert ILSTechnology com

|         |           Daniel Veillard  |
|         |           <veillard redhat |
|         |           com>             |
|         |           Sent by:         |
|         |           xml-bounces gnome|
|         |           .org             |
|         |                            |
|         |                            |
|         |           05/25/2005 03:26 |
|         |           AM               |
|         |           Please respond to|
|         |           veillard         |
  |       To:       Antti Mäkinen <antti makinen helsinki fi>                                                 
  |       cc:       xml gnome org                                                                             
  |       Subject:  Re: [xml] Problems with xmlChar* as a key in STL Map                                      

On Wed, May 25, 2005 at 09:12:08AM +0300, Antti Mäkinen wrote:
If I compare the the acquired xmlChar* with another xmlChar*, which is
created like...

  xmlChar* test = BAD_CAST "and";

...with xmlStrcmp, the result is that the strings are the same. This test

string I can use for searching a certain key in STL Map and it works. Why

is it, that the xmlChar* acquired with XPath from a node does not work
trying to find a key in STL Map? Does that have something to do with
encoding or what, or with the method that STL Map uses for comparing

  I'm a bit puzzled by your question. I do not know "STL Map", I have no
if this may have an influence. All I can tell is:
   - the xmlChar* string obtained from libxml2 is encoded in UTF-8
     (UTF-8 encoding and ASCII encoding match for characters in the ASCII
   - the string may be deallocated if you free the document or if you
     free the XPath object which was returned, I assume that's the
     problem you're facing.

   otherwise no idea.


Daniel Veillard      | Red Hat Desktop team
veillard redhat com  | libxml GNOME XML XSLT toolkit | Rpmfind RPM search engine
xml mailing list, project page
xml gnome org

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]