0

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);
}

この問題について教えてください。

  • "001" がエラーなしで受け入れられるのとは異なり、customerID は文字列として受け入れられません。しかし、CustomerID と "001" はどちらも文字列ですが、なぜこのようなことが起こるのでしょうか?
4

1 に答える 1

1

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::stringchar*に変換します(詳細についてはリンクを参照してください)。std::stringからchar *への暗黙的な変換が行われない理由については、この投稿をお読みください。

それが役に立てば幸い!

于 2016-06-29T06:24:01.067 に答える