XML to C++ data classes
C++ XML libraries such as pugixml, tinyxml2 and RapidXML are DOM or SAX parsers: they give you nodes and attribute strings, not typed objects. This XML to C++ generator writes the typed classes from a sample document, with private members, const and mutable getters, setters, std::vector for repeated elements and std::optional where a value is not always present.
Example: a 3D scene description
<scene name="level1">
<camera fov="60" x="0" y="2.5" z="-10"/>
<mesh file="tree.obj" x="4" y="0" z="3"/>
<mesh file="rock.obj" x="-2" y="0" z="7"/>
</scene>
class Camera {
std::optional<int64_t> fov;
int64_t x;
double y;
int64_t z;
std::optional<std::string> file;
// getters and setters
};
class Scene {
Camera camera;
std::vector<Camera> mesh;
std::string name;
// getters and setters
};
Notice that <camera> and <mesh> were merged into one class. They share the x, y and z attributes, so the type inference treated them as the same shape and made the attributes that only one of them has (fov, file) optional. Split them into two classes by hand if they are different concepts in your program. Also, y became double because one value was 2.5, while x and z only had whole numbers; make all coordinates double.
Filling the classes with pugixml
pugi::xml_document doc;
doc.load_string(xml.c_str());
auto sceneNode = doc.child("scene");
Scene scene;
scene.set_name(sceneNode.attribute("name").as_string());
for (auto m : sceneNode.children("mesh")) {
Camera mesh;
mesh.set_file(std::string(m.attribute("file").as_string()));
mesh.set_x(m.attribute("x").as_llong());
scene.get_mutable_mesh().push_back(mesh);
}
pugixml's as_int, as_llong, as_double and as_bool convert attribute text, and child_value() reads element text (the generator's value member). With tinyxml2 the equivalent calls are Attribute(), QueryIntAttribute() and GetText().
DOM or SAX?
For configuration files and scene descriptions like this one, a DOM parser such as pugixml is simplest: load the document, walk the nodes, fill the classes. For very large files, an event-based (SAX-style) parser such as Expat keeps memory flat; you create a Camera object on each start tag, set members from the attribute array, and push it into the scene when the element ends. Either way, the generated classes give the parsing code a clear, typed destination.
Notes
- The full-mode helpers target nlohmann/json and read the JSON form of the data, not XML.
- Include two or more of each repeated element so it becomes a
std::vector. std::optionalrequires C++17.
Format the classes with the C++ Formatter. For JSON sources, see JSON to C++. Check the XML with the XML Validator. Generation runs in your browser.