3

I trying to set the value of an element, regulary when the element looks like this <element></element> I just do this :

pugi::xml_node node = xmlBase.child("element");
pugi::xml_node nodechild = node.first_child();
nodechild.set_value(this->elementValue);

But, when I have an element looking like this:

<element />

this wont work.. i tried using this before the "set_value" row

if(nodechild == NULL)
{
    nodechild = node.append_child();
}

but this will create a new element within that element, and I dont want to do this,

Perhaps my fist approach is even wrong? how do you properly set the value of the element?

Tistatos
  • 621
  • 1
  • 6
  • 16

2 Answers2

7

Seems like the Solution is to do this:

nodechild = node.append_child(pugi::node_pcdata);

this will create a child thats only plain text within the element

Tistatos
  • 621
  • 1
  • 6
  • 16
  • 2
    That's correct; as per http://pugixml.googlecode.com/svn/tags/latest/docs/manual/dom.html#node_pcdata text inside the elements has its own node; has no child nodes ( also has none; x has a PCDATA child), so you need to explicitly append the node with the correct type. – zeuxcg Mar 30 '11 at 18:26
3

You should check to see if the child element is equal to the null_node before you try to set the value. If it is null_node you should append_child instead:

xml_node firstchild = node.first_child();
if( !firstchild )
{
  firstchild.append_child(pugi::node_pcdata).set_value("foo");
}
else
{
  firstchild.set_value("foo");
}
Skrymsli
  • 4,589
  • 5
  • 30
  • 33