1

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

Keivan
  • 673
  • 7
  • 15

1 Answers1

2

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).

dquam
  • 101
  • 4
  • I thought that the root always has to be a XMLNode, was confusing a bit. Thanks. – Keivan May 03 '16 at 15:27
  • What I find confusing is that the root of an XML is always seen as a Node in tinyxml2. So this problem occurs while parsing XML as well. There to get the first child you need to pass it to a `XMLNode`. How do you solve it there? – Keivan May 04 '16 at 11:00
  • XMLNode is an [abstract class](https://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes) which means every XMLNode has to be one of the derived classes as well. There are built in cast methods to discover which derived class a particular XMLNode is (e.g. `ToElement()`, `ToDocument()`, etc.). Also, if this answered your question, please mark it as such. – dquam May 05 '16 at 15:10