Saving values using ofXml

Hi! i’m using ofXml example, trying to set a value but is not saving any value is this the right way to do it?

bg = drawing.findFirst("background[red and green and blue]");
if(!bg){
	// remove any possible malformed background tag
	drawing.removeChild("background");

	// create the correct background tag and add color components
	bg = drawing.appendChild("background");
	bg.appendChild("red").set(255);
	bg.appendChild("green").set(255);
	bg.appendChild("blue").set(255);
    
    xml.save("points.xml");

Hi, that code was taken from the example but if you just took parts of it you must be careful. If the code that you are using is just what you posted then it will probably wont work. That code assumes that you’ve loaded an xml with the background tag. if you simply want to write and not update a file, you can just do .

ofXml xml;
auto data = xml.appendChild("data");// or whatever name you want to.
data.appendChild("red").set(255);
data.appendChild("green").set(255);
data.appendChild("blue").set(255);

xml.save("points.xml");

this will out put a file with the following contents

<?xml version="1.0"?>
<data>
	<red>255</red>
	<green>255</green>
    <blue>255</blue>
</data>

for reading

ofXml xml2;
xml2.load("points.xml");

auto values = xml2.getChild("data");
if(values){
// just print the values but you can do what ever you want with these.
	cout << values.getChild("red").getIntValue() << endl;
	cout << values.getChild("green").getIntValue() << endl;
	cout << values.getChild("blue").getIntValue() << endl;
}
1 Like