【问题标题】:TinyXML2 SetAttribute Can't Accept String Object?TinyXML2 SetAttribute 不能接受字符串对象?
【发布时间】:2016-03-18 16:50:42
【问题描述】:

我正在使用 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);
}

请在这个问题上赐教。

  • customerID 不被接受为字符串,不像“001”被接受且没有错误。但是CustomerID和“001”都是字符串,为什么会这样呢?

【问题讨论】:

  • 请详细说明“不工作”的含义。包括您收到的确切错误消息和customerID 的确切值。

标签: xml setattribute tinyxml2


【解决方案1】:

如您所见,阅读 tinyxml2.hSetAttribute 的各种定义包括:

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::stringchar * 的隐式转换的原因的讨论,我邀请您阅读此post

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多