C++ class for reading and writing XML structures. No need for a C++ code parser or special pre compiler. Specify a schema entirly in native C++. The schema is verified when XML is read and exceptions are thrown when the XML to be parse is invalid.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.6 KiB

/*! @file
@id $Id$
*/
// 1 2 3 4 5 6 7 8
// 45678901234567890123456789012345678901234567890123456789012345678901234567890
// g++ -I../../src ../../src/xml.cxx serialization.cxx
#include <xml-cxx/xml.hxx>
#include <iostream>
#include <sstream>
//! Class with built in xml::Serialize as member, no inheritance
class A {
public:
A(): _ser("a") {
_ser.persist(a, "a");
_ser.persist(txt, "txt");
}
int a;
std::string txt;
xml::Serialize _ser;
};
//! Class that inherits xml::Serialize
class B: public xml::Serialize {
public:
int a;
std::string txt;
protected:
void initXmlMembers() {
className("b");
persist(a, "a");
persist(txt, "txt");
}
};
//! Class with external xml::Serialize
class C {
public:
int a;
std::string txt;
};
int main(int, char**) {
{ // Serialization as a member
std::stringstream ss("<a>\n"
"\t<a>1234</a>\n"
"\t<txt>Dies ist ein Serialisierungs-Test</txt>\n"
"</a>");
A a;
a._ser.loadXml(ss);
if (a.a==1234) a.a=4321;
a._ser.saveXml(std::cout)<<std::endl;
} { // Inherited Serialization
std::stringstream ss("<b>\n"
"\t<a>1234</a>\n"
"\t<txt>Dies ist ein Serialisierungs-Test</txt>\n"
"</b>");
B b;
b.loadXml(ss);
if (b.a==1234) b.a=4321;
b.saveXml(std::cout)<<std::endl;
} { // External xml::Serialize: "ser" must live in no longer than "c"!
std::stringstream ss("<c>\n"
"\t<a>1234</a>\n"
"\t<txt>Dies ist ein Serialisierungs-Test</txt>\n"
"</c>");
C c;
xml::Serialize ser(xml::Serialize("c")
.persist(c.a, "a")
.persist(c.txt, "txt"));
ser.loadXml(ss);
if (c.a==1234) c.a=4321;
ser.saveXml(std::cout)<<std::endl;
} { // Use xml::Serialize to store anything, e.g. local variables
// Important: "ser" must live in no longer than the variables!
std::stringstream ss("<d>\n"
"\t<a>1234</a>\n"
"\t<txt>Dies ist ein Serialisierungs-Test</txt>\n"
"</d>");
int a;
std::string txt;
xml::Serialize ser(xml::Serialize("d")
.persist(a, "a")
.persist(txt, "txt"));
ser.loadXml(ss);
if (a==1234) a=4321;
ser.saveXml(std::cout)<<std::endl;
}
return 0;
}