Examples › General Examples
general_xml_parser
Legacy: examples_general/xml_parser/testprog.cpp · Modern: examples_modern/general/xml_parser/modern.cpp
Modern equivalent of the gxsXML DOM test: build a tree, write it to a file, load the file back and write it again. The standard library has no XML parser, so this shows the modern C++ for the parts a program owns: the tree is a struct whose children are a std::vector of nodes (no AddChild()/AddSibling() pointers to free), attributes are a std::map, output escapes the five XML special characters, and the loader is a small recursive descent parser over std::string_view that reports errors with an exception. It reads elements, attributes, text, comments and CDATA; it does not read DTDs or entities beyond the five predefined ones. For production XML use a library (libxml2, pugixml, tinyxml2, Xerces) or keep gxsXML.
Usage: modern file.xml (load and print), or no arguments for the build-write-load-compare test.
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxString / UString | std::string, std::string_view | C++98 / C++17 | string_view looks at text without copying it. |
| gxList, gxListNode | std::list; splice() for MoveBefore()/MoveAfter() | C++98 | The list owns its nodes: no DestroyList()/DestroyArrayList(). |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_general/xml_parser/testprog.cpp 412 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include <stdlib.h> #include "gxsxml.h" #include "gxsrss.h" #include "gxstring.h" #include "gxs_ver.h" #ifdef __MSVC_DEBUG__ #include "leaktest.h" #endif // Version number and program name gxString ProgramVersionNumber; gxString ProgramName = "gxsXML test program"; // Program globals gxString program_run_name; gxString outfile; int write_test_file = 0; void HelpMessage() { cout << "\n"; cout << ProgramName.c_str() << " version " << ProgramVersionNumber << "\n"; cout << "Usage: " << program_run_name << " [switches] infile.xml" << "\n"; cout << "Example: " << program_run_name << " testfile.xml" << "\n"; cout << "Switches: " << "\n"; cout << " -? = Display this help message and exit." << "\n"; cout << " -t = Build and write a test XML file." << "\n"; cout << " -w\"outfile.xml\" = Write a copy of the in-memory tree" << "\n"; cout << "\n"; return; } int ProcessArgs(int argc, char *argv[]) { // process the program's argument list int i; for(i = 1; i < argc; i++ ) { if(*argv[i] == '-') { char sw = *(argv[i] +1); switch(sw) { case '?': HelpMessage(); return 0; // Signal program to exit case 't': write_test_file = 1; break; case 'w': outfile = argv[i]+2; break; default: cout << "\n" << flush; cout << "Unknown command line switch " << argv[i] << "\n" << flush; cout << "Exiting..." << "\n" << flush; cout << "\n" << flush; return 0; } } } return 1; // All command line arguments were valid } void PrintDocInfo(gxsXML &xml); void PrintPIList(gxsXML &xml); void PrintDTDList(gxsXML &xml); void PrintCDATA(gxsXML &xml); void PrintComments(gxsXML &xml); void PrintXS(gxsXML &xml); void PrintTree(gxsXML &xml); int WriteTestTree(const char *outfile); // Program's main thread of execution. // ----------------------------------------------------------- int main(int argc, char **argv) // NOTE: None of the MSVC compilers will expand wildcard characters // used in command-line arguments unless linked with the setargv.obj // library. All the UNIX compilers will expand wildcard characters // by default. { #ifdef __MSVC_DEBUG__ InitLeakTest(); #endif // Set this program's runtime name and version number program_run_name = argv[0]; ProgramVersionNumber << clear << gxSocketVersion; if(argc < 2) { HelpMessage(); return 1; } // Process command ling arguments and files gxString fname; int narg; char *arg = argv[narg = 1]; while(narg < argc) { if(arg[0] != '\0') { if(arg[0] == '-') { // Look for command line arguments // Exit if argument is not valid or argument signals program to exit if(!ProcessArgs(argc, argv)) return 1; } else { fname = arg; } } arg = argv[++narg]; } gxsXML xml; if(fname.is_null()) { if(write_test_file) { cout << "No output file name specified on the command line" << "\n" << flush; } else { cout << "No input file name specified on the command line" << "\n" << flush; } return 1; } if(write_test_file) { // Write our test tree and exit if(!WriteTestTree(fname.c_str())) return 1; return 0; } // Read and parse an existing XML file cout << "Loading XML file..." << "\n" << flush; if(!xml.LoadXMLFile(fname.c_str())) { cout << "Error loading XML file" << "\n" << flush; cout << xml.GetError() << "\n"; return 1; } PrintDocInfo(xml); cout << "\n" << flush; PrintPIList(xml); cout << "\n" << flush; PrintDTDList(xml); cout << "\n" << flush; PrintCDATA(xml); cout << "\n" << flush; PrintComments(xml); cout << "\n" << flush; PrintXS(xml); cout << "\n" << flush; PrintTree(xml); cout << "\n" << flush; if(!outfile.is_null()) { cout << "\n" << flush; cout << "Writing a copy of the XML file to " << outfile.c_str() << "\n" << flush; if(!xml.WriteXMLFile(outfile.c_str())) { cout << "Error writing XML file" << "\n" << flush; cout << xml.GetError() << "\n"; return 1; } cout << "Write complete" << "\n"; } return 0; } void PrintDocInfo(gxsXML &xml) { cout << "XML Doc Info" << "\n" << flush; cout << "------------" << "\n" << flush; cout << "File name: " << xml.doc_info.fname << "\n" << flush; cout << "Version: " << xml.doc_info.xml_version_str << "\n" << flush; cout << "Enoding: " << xml.doc_info.xml_encoding << "\n" << flush; if(!xml.doc_info.xml_style_sheet.is_null()) { cout << "Style Sheet: " << xml.doc_info.xml_style_sheet << "\n" << flush; } else { cout << "Style Sheet: None" << "\n" << flush; } cout << "Standalone: " << xml.doc_info.xml_standalone << "\n" << flush; } void PrintPIList(gxsXML &xml) { if(xml.pi_list.IsEmpty()) { cout << "Process instruction list is empty" << "\n"; cout << "---------------------------------" << "\n"; return; } gxListNode<gxsXMLNode> *pi_ptr = xml.pi_list.GetHead(); cout << "Process instruction list" << "\n"; cout << "------------------------" << "\n"; while(pi_ptr) { cout << "Tag: " << pi_ptr->data.attributes.c_str() << "\n"; pi_ptr = pi_ptr->next; } } void PrintDTDList(gxsXML &xml) { if(xml.dtd_list.IsEmpty()) { cout << "Document type declaration list is empty" << "\n"; cout << "--------------------------------------" << "\n"; return; } gxListNode<gxsXMLNode> *dtd_ptr = xml.dtd_list.GetHead(); cout << "Document type declaration list" << "\n"; cout << "------------------------------" << "\n"; while(dtd_ptr) { cout << dtd_ptr->data.attributes.c_str() << "\n"; dtd_ptr = dtd_ptr->next; } cout << "------------------------------" << "\n"; } void PrintCDATA(gxsXML &xml) { if(xml.cdata_list.IsEmpty()) { cout << "CDATA list is empty" << "\n"; cout << "-------------------" << "\n"; return; } gxListNode<gxsXMLNode> *cdata_ptr = xml.cdata_list.GetHead(); cout << "CDATA list" << "\n"; cout << "----------" << "\n"; while(cdata_ptr) { cout << cdata_ptr->data.attributes.c_str() << "\n"; cdata_ptr = cdata_ptr->next; } cout << "----------" << "\n"; } void PrintComments(gxsXML &xml) { if(xml.comment_list.IsEmpty()) { cout << "Comment list is empty" << "\n"; cout << "---------------------" << "\n"; return; } gxListNode<gxsXMLNode> *comment_ptr = xml.comment_list.GetHead(); cout << "Comment list be for root node" << "\n"; cout << "-----------------------------" << "\n"; while(comment_ptr) { cout << comment_ptr->data.attributes.c_str() << "\n"; comment_ptr = comment_ptr->next; } cout << "-----------------------------" << "\n"; } void PrintXS(gxsXML &xml) { if(xml.xs.IsEmpty()) { cout << "No XML Schema" << "\n"; cout << "------------" << "\n"; return; } gxString xs_string; cout << "XML Schema" << "\n"; cout << "------------" << "\n"; if(!xml.WriteXS(xs_string)) { cout << xml.GetError() << "\n"; } else { cout << xs_string.c_str() << "\n"; } cout << "------------" << "\n"; } void PrintTree(gxsXML &xml) // 10/14/2026: Print the tree with the library's own writer. The old // hand-written loop repeated the writer's earlier nesting logic, so it // showed nested elements at the wrong level once the parser was fixed. { gxString tree; if(!xml.WriteTree(tree)) { cout << xml.GetError() << "\n"; return; } cout << tree.c_str(); } int WriteTestTree(const char *outfile) { gxsXML xml; cout << "Building a test XML tree" << "\n" << flush; xml.Clear(); // Clear the tree and headers before creating a new tree // Add our root node gxsXMLNode *root_node = xml.AddRoot("xmlroot"); if(!root_node) { // Check for any errors adding the root node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } gxsXMLNode *n; // Add a parent node with no attraibutes or data n = xml.AddParent("Author"); if(!n) { // Check for any errors adding the node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } // Add a parent with no attributes, with data n = xml.AddParent("publisher", 0, "DataReel Software Development Group"); // Add a parent node with attraibutes and child nodes n = xml.AddParent("support1", "link=\"http://www.example.com\""); gxsXMLNode_t *element = xml.AddChild(n, "email", 0, "example@example.com"); if(!element) { // Check for any errors adding the node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } element = xml.AddChild(n, "name", 0, "support"); element = xml.AddChild(n, "fax", 0, "fax number"); // Add a parent with children and child siblings n = xml.AddParent("subtree_depth_test"); // Add the child element = xml.AddChild(n, "email", "accountinfo=\"datareel\""); // Add a sub-child gxsXMLSubElement *sub_element = xml.AddSubChild(element, "username", 0, "uname"); if(!sub_element) { // Check for any errors adding the node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } sub_element = xml.AddSubChild(element, "server"); // Add the sub-child siblings gxsXMLSubElement *sibling = xml.AddSibling(element, sub_element, "hostname", 0, "pop3 host"); if(!sibling) { // Check for any errors adding the node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } sibling = xml.AddSibling(element, sub_element, "pop3"); xml.AddSibling(element, sibling, "port", 0, "default"); xml.AddSibling(element, sibling, "usessl", 0, "yes"); // Add a sibling to the sub-child sibling gxsXMLSubElement *subsibling = xml.AddSibling(element, sibling, "local"); if(!subsibling) { // Check for any errors adding the node cout << "Error adding node to XML tree" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } // Add sub-siblings to the sibling xml.AddSibling(element, subsibling, "filters", 0, "yes"); xml.AddSibling(element, subsibling, "arch_dir", 0, "local"); cout << "Writing a copy of the XML tree to " << outfile << "\n" << flush; if(!xml.WriteXMLFile(outfile)) { cout << "Error writing XML file" << "\n" << flush; cout << xml.GetError() << "\n"; return 0; } cout << "Write complete" << "\n"; return 1; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++17)
examples_modern/general/xml_parser/modern.cpp 217 lines
#include <cstdio> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <string_view> #include <vector> struct Node { std::string name; std::map<std::string, std::string> attributes; std::string text; std::vector<Node> children; // C++17: vector of an incomplete type Node &add_child(std::string n, std::string t = {}) { children.push_back(Node{std::move(n), {}, std::move(t), {}}); return children.back(); } }; std::string escape(std::string_view s) { std::string r; for(char c : s) { switch(c) { case '&': r += "&"; break; case '<': r += "<"; break; case '>': r += ">"; break; case '"': r += """; break; case '\'': r += "'"; break; default: r += c; } } return r; } void write(std::ostream &os, const Node &n, int depth = 0) { std::string indent(std::size_t(depth) * 2, ' '); os << indent << '<' << n.name; for(const auto &[k, v] : n.attributes) os << ' ' << k << "=\"" << escape(v) << '"'; if(n.children.empty() && n.text.empty()) { os << "/>\n"; return; } os << '>' << escape(n.text); if(!n.children.empty()) { os << '\n'; for(const auto &c : n.children) write(os, c, depth + 1); os << indent; } os << "</" << n.name << ">\n"; } class Parser { public: explicit Parser(std::string_view s) : s_(s) {} Node parse_document() { skip_misc(); Node root = parse_element(); skip_misc(); if(pos_ != s_.size()) fail("text after the root element"); return root; } private: [[noreturn]] void fail(const std::string &what) { throw std::runtime_error("XML error at offset " + std::to_string(pos_) + ": " + what); } bool starts(std::string_view p) const { return s_.substr(pos_, p.size()) == p; } void skip_ws() { while(pos_ < s_.size() && std::string_view(" \t\r\n").find(s_[pos_]) != std::string_view::npos) pos_++; } void skip_past(std::string_view end) { auto e = s_.find(end, pos_); if(e == std::string_view::npos) fail("missing " + std::string(end)); pos_ = e + end.size(); } void skip_misc() { // Declarations, comments and white space for(;;) { skip_ws(); if(starts("<?")) skip_past("?>"); else if(starts("<!--")) skip_past("-->"); else if(starts("<!DOCTYPE")) skip_past(">"); else return; } } std::string name() { std::size_t start = pos_; while(pos_ < s_.size() && std::string_view(" \t\r\n/>=").find(s_[pos_]) == std::string_view::npos) pos_++; if(pos_ == start) fail("expected a name"); return std::string(s_.substr(start, pos_ - start)); } std::string unescape(std::string_view t) { std::string r; for(std::size_t i = 0; i < t.size(); i++) { if(t[i] != '&') { r += t[i]; continue; } auto semi = t.find(';', i); if(semi == std::string_view::npos) fail("bad entity"); std::string_view e = t.substr(i, semi - i + 1); if(e == "&") r += '&'; else if(e == "<") r += '<'; else if(e == ">") r += '>'; else if(e == """) r += '"'; else if(e == "'") r += '\''; else fail("unknown entity " + std::string(e)); i = semi; } return r; } Node parse_element() { if(!starts("<")) fail("expected '<'"); pos_++; Node n; n.name = name(); for(;;) { skip_ws(); if(starts("/>")) { pos_ += 2; return n; } if(starts(">")) { pos_++; break; } std::string key = name(); skip_ws(); if(!starts("=")) fail("expected '='"); pos_++; skip_ws(); if(pos_ >= s_.size() || (s_[pos_] != '"' && s_[pos_] != '\'')) fail("expected a quote"); char q = s_[pos_++]; auto end = s_.find(q, pos_); if(end == std::string_view::npos) fail("unterminated attribute"); n.attributes[key] = unescape(s_.substr(pos_, end - pos_)); pos_ = end + 1; } for(;;) { // Content if(pos_ >= s_.size()) fail("missing </" + n.name + ">"); if(starts("</")) { pos_ += 2; if(name() != n.name) fail("mismatched end tag for " + n.name); skip_ws(); if(!starts(">")) fail("expected '>'"); pos_++; auto b = n.text.find_first_not_of(" \t\r\n"); // Trim the text n.text = b == std::string::npos ? "" : n.text.substr(b, n.text.find_last_not_of(" \t\r\n") - b + 1); return n; } if(starts("<!--")) { skip_past("-->"); continue; } if(starts("<![CDATA[")) { pos_ += 9; auto end = s_.find("]]>", pos_); if(end == std::string_view::npos) fail("unterminated CDATA"); n.text += s_.substr(pos_, end - pos_); pos_ = end + 3; continue; } if(starts("<")) { n.children.push_back(parse_element()); continue; } auto next = s_.find('<', pos_); if(next == std::string_view::npos) next = s_.size(); n.text += unescape(s_.substr(pos_, next - pos_)); pos_ = next; } } std::string_view s_; std::size_t pos_ = 0; }; Node load(const std::string &fname) { std::ifstream in(fname, std::ios::binary); if(!in) throw std::runtime_error("cannot open " + fname); std::ostringstream ss; ss << in.rdbuf(); std::string doc = ss.str(); return Parser(doc).parse_document(); } int main(int argc, char **argv) { try { if(argc > 1) { write(std::cout, load(argv[1])); return 0; } Node root{"Headlines", {}, {}, {}}; // AddRoot() root.add_child("Author"); root.add_child("publisher", "DataReel Software Development Group"); Node &h = root.add_child("Headline"); // AddChild() h.add_child("Title", "News Headlines & <Updates>"); Node &s = h.add_child("support1"); s.attributes["link"] = "http://www.example.com/?a=1&b=2"; s.add_child("email", "example@example.com"); s.add_child("name", "support name"); const std::string fname = "modern_testfile.xml"; { std::ofstream out(fname); out << "<?xml version=\"1.0\"?>\n"; write(out, root); // WriteXMLFile() } Node back = load(fname); // LoadXMLFile() std::ostringstream a, b; write(a, root); write(b, back); std::cout << b.str(); std::cout << (a.str() == b.str() ? "Loaded tree matches the written tree\n" : "MISMATCH\n"); std::remove(fname.c_str()); return a.str() == b.str() ? 0 : 1; } catch(const std::exception &e) { std::cout << e.what() << "\n"; return 1; } } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17 cmake --build build-modern --target general_xml_parser ./build-modern/general_xml_parser # or without CMake: g++ -std=c++17 -pthread -o general_xml_parser examples_modern/general/xml_parser/modern.cpp
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
<Headlines>
<Author/>
<publisher>DataReel Software Development Group</publisher>
<Headline>
<Title>News Headlines & <Updates></Title>
<support1 link="http://www.example.com/?a=1&b=2">
<email>example@example.com</email>
<name>support name</name>
</support1>
</Headline>
</Headlines>
Loaded tree matches the written tree