This example demonstrates how to parse XML documents using the DocWire SDK modern C++ API.
#include "docwire.h"
#include <iostream>
#include <string>
#include <ranges>
#include <algorithm>
int main()
{
std::string xml_data = R"(
<catalog>
<product id="101" category="electronics">
<name>Smartphone</name>
<price currency="USD">699.99</price>
<stock>50</stock>
</product>
<product id="102" category="books">
<name>C++ Programming</name>
<price currency="USD">49.99</price>
<stock>120</stock>
</product>
</catalog>
)";
try
{
int products_found = 0;
xml::reader reader(xml_data);
| std::views::filter([](auto n) { return n.name() == "product"; });
for (auto product_node : products)
{
{
if (attr.name() == "id")
{
non_negative<int> id = convert::to<int>(attr);
}
}
non_negative<int> id = *xml::attribute_value<int>(product_node, "id");
if (
id == 102)
enforce(category ==
"books",
"category"_v = category);
auto name = std::ranges::find_if(
children, [](
auto n) {
return n.name() ==
"name"; })->string_value();
if (
id == 101)
enforce(name ==
"Smartphone",
"name"_v = name);
else if (
id == 102)
enforce(name ==
"C++ Programming",
"name"_v = name);
auto price_node = std::ranges::find_if(
children, [](
auto n) {
return n.name() ==
"price"; });
double price = convert::to<double>(*price_node);
enforce(currency ==
"USD",
"currency"_v = currency);
if (
id == 101)
enforce(price > 699 && price < 700,
"price");
products_found++;
}
}
return 0;
}
DOCWIRE_CORE_EXPORT std::string diagnostic_message(const std::exception &e)
Generates a diagnostic message for the given nested exceptions chain.
node_ref< safety_level > root_element(reader< safety_level > &reader)
Finds and returns the root element of the XML document.
attributes_view< safety_level > attributes(const node_ref< safety_level > &node)
A factory function to create an attributes_view with a specified safety policy.
children_view< safety_level > children(const node_ref< safety_level > &node)
Returns a view of the direct children of the given node.
checked< std::optional< std::string_view >, safety_level > attribute_value(const node_ref< safety_level > &node, std::string_view name)
A convenience helper to find an attribute by name.
The main namespace for the DocWire SDK.
void enforce(detail::with_source_location< bool > condition, Context &&... context)
Enforces a condition based on the safety policy.