ofXml setAttribute on root XML node produces anonymous tag

Hi! This code:

void ofxPolySave(const ofPolyline & poly, string xmlPath) {
    ofXml xml;
    auto data = xml.appendChild("poly");
    //data.setAttribute("closed", ofToString(poly.isClosed()));            
    for(auto & point : poly.getVertices()) {
        auto p = data.appendChild("point");
        p.setAttribute("x", ofToString(point.x));
        p.setAttribute("y", ofToString(point.y));
    }    
    data.setAttribute("closed", ofToString(poly.isClosed()));            
    xml.save(xmlPath);
}

produces this file:

<?xml version="1.0"?>
<poly>
        <point x="226" y="483" />
        <point x="378" y="420" />
        <point x="508" y="494" />
        <point x="442" y="565" />
</poly>
<:anonymous closed="0" />

?
Note the <:anonymous /> tag at the end.

If I move the .setAttribute line up before the for loop, all the point tags go inside the anonymous tag. Different error, but no better.

I can’t find anything about anonymity in xml :stuck_out_tongue: nor the word anonymous in the whole source of openframeworks.

Any ideas?

Found a hint at https://pugixml.org/docs/quickstart.html

In order to guard against forgotten node/attribute names, empty node/attribute names are printed as “:anonymous”.

But not sure what to do about that…

It seems like ofXml.cpp doesn’t want attributes added to the root node, based on this code:

//ofXml.cpp:155
ofXml::Attribute ofXml::appendAttribute(const std::string & name){
	if(xml==doc->document_element()){
		xml = doc->append_child(pugi::node_element);
	}
	return this->xml.append_attribute(name.c_str());
}

ofXml::Attribute ofXml::prependAttribute(const std::string & name){
	if(xml==doc->document_element()){
		xml = doc->append_child(pugi::node_element);
	}
	return this->xml.prepend_attribute(name.c_str());
}

If I remove those if statements it works fine. Why does it create a new element if we try adding an attribute to the root node?

A root node with attributes should be valid XML code, afaik.

i think this is just a bug probably from copy pasting the code to append a tag, if it’s the root node there shouldn’t be other tags after it but as you say an attribute should be ok, can you send a PR?

Sure! PR here: https://github.com/openframeworks/openFrameworks/pull/5730