我正在使用TinyXML2而我正面临SetAttribute
的问题。
它接受字符串文字(即"001"
)但不接受字符串变量。
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);
}
请在这个问题上赐教。
答案 0 :(得分:0)
正如您可以看到阅读 tinyxml2.h 一样, SetAttribute 的各种定义包括:
void SetAttribute( const char* name, const char* value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
因此,您需要更改 customerID 的代码,如下所示:
p1Element->SetAttribute("ID", customerID.c_str());
其中c_str()实质上将 std :: string 转换为 char * (有关详细信息,请参阅链接)。有关没有从 std :: string 到 char * 的隐式转换的原因的讨论,我邀请您阅读此post。
希望它有所帮助!