2

I'm trying to convert a string to an xmlChar. The compiler says no suitable conversion function from const string to xmlChar exists. This is what the code looks like:

bool ClassName::openFile(const String& ZipFile) { //convert const xmlChar *temp = (const xmlChar)ZipFile; //ZipFile has an error here. ZipFile is path and filename ... } 

Any ideas? I googled it and people were converting from xmlChar to string but not this direction.

5
  • 1
    Possibly const xmlChar *temp = (const xmlChar*)(ZipFile.c_str()); Commented Nov 5, 2014 at 19:41
  • 2
    using C style cast with C++ is frowned upon as being poor coding style since it is a source of defects. I suspect you wanted to do something like const xmlChar *temp = (const xmlChar *)ZipFile.c_str();? see how to convert a std::string to const char or char Commented Nov 5, 2014 at 19:42
  • This is impossible to answer unless you provide the definitions of String and xmlChar, too. Commented Nov 5, 2014 at 20:12
  • xmlChar is part of libxml2. Thanks to @Christophe for editing the tags. What R Sahu and Richard Chambers suggested was a great help. I'm all set. Thanks! string is std::string for us. Commented Nov 5, 2014 at 20:26
  • string temp1 = "hello"; const xmlChar *temp = (const xmlChar *)temp1.c_str(); Commented Nov 5, 2014 at 20:27

3 Answers 3

3

xmlChar is just a typedef of unsigned char. Just make your sentence like this:

const xmlChar *temp = ZipFile.c_str(); 
Sign up to request clarification or add additional context in comments.

Comments

0

unsafe but removed overhead.

xmlChar *temp = reinterpret_cast<xmlChar*>(ZipFile); 

but you must be aware of usage of reinterpret_cast

Comments

0

This xml library was written for standard C. There are c style casting methods used at the time that took advantage of the BAD_CAST keyword in the library. Example:

rc = xmlTextWriterWriteElement(writer, BAD_CAST "Value1", BAD_CAST "DATA1"); if (rc < 0) { throw EXCEPTION("Error in xmlTextWriterWriteElement"); } 

But with c++ if you want to avoid the c-style cast the best you can do is:

rc = xmlTextWriterWriteElement(writer, const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("Value1")), const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("DATA1"))); 

Note that the usual dangers of this casting aren't a problem due to the use case here. We can safely assume the underlying library isn't going to do anything nasty to us.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.