0

I'm using TinyXML2 and I'm facing an issue with SetAttribute.

It accepts a string literal (i.e. "001") but not a string variable.

void createDoc(string customerID, string name) {
    XMLDocument doc;
    XMLNode * pRoot = doc.NewElement("containerRequirement");
    doc.InsertFirstChild(pRoot);

    XMLElement * p1Element = doc.NewElement("customer"); // Start customer

    p1Element->SetAttribute("ID", customerID); // not working
    p1Element->SetAttribute("ID", "001");      // working

    XMLElement * p2Element = doc.NewElement("name");
    cout << "NAME is: " << name << endl;
    p2Element->SetText(name);
}

Please enlighten me on this issue.

  • customerID is not accepted as a String unlike "001" is accepted with no errors. But both CustomerID and "001" are strings, why does this happen?
Amos Tan
  • 1
  • 2
  • Please detail what "not working" means. Include the exact error message you get and the exact value of `customerID`. – Tomalak Mar 18 '16 at 17:00

1 Answers1

2

As you can see reading tinyxml2.h, among the various definitions for SetAttribute is:

void SetAttribute( const char* name, const char* value )    {
    XMLAttribute* a = FindOrCreateAttribute( name );
    a->SetAttribute( value );
}

Consequently, you will need to change your code for customerID as follows:

 p1Element->SetAttribute("ID", customerID.c_str());

where c_str() essentially converts an std::string to a char* (see the link for further details). For a discussion of the reason why there is no implicit conversion from std::string to char *, I invite you to read this post.

Hope it helps!

Community
  • 1
  • 1
Lorenzo Addazi
  • 325
  • 3
  • 12