|
| 1 | +#include <cstdio> |
| 2 | +#include <sstream> |
| 3 | +#include <string> |
| 4 | + |
| 5 | +#include <pugixml.hpp> |
| 6 | + |
| 7 | +static_assert(PUGIXML_VERSION == 1160, "expected pugixml 1.16 headers"); |
| 8 | + |
| 9 | +int main() { |
| 10 | + bool ok = true; |
| 11 | + |
| 12 | + const char *xml = R"(<?xml version="1.0" encoding="UTF-8"?> |
| 13 | +<catalog> |
| 14 | + <book id="1" price="19.99"><title>Alpha</title></book> |
| 15 | + <book id="2" price="29.50"><title>Beta</title></book> |
| 16 | +</catalog>)"; |
| 17 | + |
| 18 | + pugi::xml_document doc; |
| 19 | + pugi::xml_parse_result res = doc.load_string(xml); |
| 20 | + if (!res) { |
| 21 | + std::fprintf(stderr, "pugixml load_string failed: %s\n", res.description()); |
| 22 | + return 1; |
| 23 | + } |
| 24 | + |
| 25 | + // DOM traversal and typed attributes |
| 26 | + pugi::xml_node catalog = doc.child("catalog"); |
| 27 | + ok = ok && catalog; |
| 28 | + pugi::xml_node first = catalog.child("book"); |
| 29 | + ok = ok && first.attribute("id").as_int() == 1; |
| 30 | + ok = ok && std::string(first.child_value("title")) == "Alpha"; |
| 31 | + |
| 32 | + // XPath query |
| 33 | + pugi::xpath_node match = doc.select_node("/catalog/book[@id='2']/title"); |
| 34 | + ok = ok && match && std::string(match.node().child_value()) == "Beta"; |
| 35 | + |
| 36 | + // Mutation and serialization |
| 37 | + pugi::xml_node added = catalog.append_child("book"); |
| 38 | + added.append_attribute("id") = 3; |
| 39 | + added.append_child("title").text().set("Gamma"); |
| 40 | + |
| 41 | + std::ostringstream oss; |
| 42 | + doc.save(oss, " ", pugi::format_raw); |
| 43 | + const std::string out = oss.str(); |
| 44 | + ok = ok && out.find("<book id=\"3\"><title>Gamma</title></book>") != std::string::npos; |
| 45 | + |
| 46 | + // Malformed XML rejection |
| 47 | + pugi::xml_document bad; |
| 48 | + pugi::xml_parse_result bad_res = bad.load_string("<unclosed>"); |
| 49 | + ok = ok && !bad_res && bad_res.status != pugi::status_ok; |
| 50 | + |
| 51 | + return ok ? 0 : 1; |
| 52 | +} |
0 commit comments