c++xmltinyxmltinyxml2

Tinyxml2 root setattribute


I have been trying to set an attribute for the root in an XML doc using tinyxml2.

In tinyxml, the following code

TiXmlDocument doc;

TiXmlElement * root = new TiXmlElement( "ROOT" );


root->SetAttribute("msg","ImFree");
doc.LinkEndChild( root );

TiXmlElement * element = new TiXmlElement( "CHILD" );
TiXmlText * text = new TiXmlText( "Message" );
element->LinkEndChild( text );
root->LinkEndChild( element );


doc.SaveFile( "foo.xml" );

generates the following xml file:

<ROOT msg="ImFree">
    <CHILD>Message</CHILD> 
</ROOT>

However I still have no idea how to set the attribute of the root in tinyxml2. I have the following code:

tinyxml2::XMLDocument xml_doc;

tinyxml2::XMLNode * p_root = xml_doc.NewElement("ROOT");
xml_doc.InsertFirstChild(p_root);


tinyxml2::XMLElement * p_element = xml_doc.NewElement("CHILD");
p_element->SetText("Message");
p_root->InsertEndChild(p_element);

Which generates :

<ROOT>
    <CHILD>Message</CHILD>
</ROOT>

Now if I write p_root->SetText();, p_root->SetValue(); or SetAttribute, all give an error that class tinyxml2::XMLNode has no member named SetText or SetValue or SetAttribute.

I searched hard to find the answer online, but couldn't find it.

Thanks

Cheers


Solution

  • Try changing your line tinyxml2::XMLNode * p_root = xml_doc.NewElement("ROOT"); to tinyxml2::XMLElement * p_root = xml_doc.NewElement("ROOT");. XMLNode does not have a SetAttribute method, only XMLElement does (http://www.grinninglizard.com/tinyxml2docs/tinyxml2_8h_source.html).