I have a bunch of hierarchical data stored in an XML file. I am wrapping that up behind hand-crafted classes using TinyXML. Given an XML fragment that describes a source signature as a set of (frequency, level) pairs a bit like this:
<source>
<sig><freq>1000</freq><level>100</level><sig>
<sig><freq>1200</freq><level>110</level><sig>
</source>
i am extracting the pairs with this:
std::vector< std::pair<double, double> > signature() const
{
std::vector< std::pair<double, double> > sig;
for (const TiXmlElement* sig_el = node()->FirstChildElement ("sig");
sig_el;
sig_el = sig_el->NextSiblingElement("sig"))
{
const double level = boost::lexical_cast<double> (sig_el->FirstChildElement("level")->GetText());
const double freq = boost::lexical_cast<double> (sig_el->FirstChildElement("freq")->GetText());
sig.push_back (std::make_pair (freq, level));
}
return sig;
}
where node() is pointing at the <source>
node.
Question: would I get a neater, more elegant, more maintainable or in any other way better piece of code using an XPath library instead?
Update: I have tried it using TinyXPath two ways. Neither of them actually work, which is a big point against them obviously. Am I doing something fundamentally wrong? If this is what it is going to look like with XPath, I don't think it is getting me anything.
std::vector< std::pair<double, double> > signature2() const
{
std::vector< std::pair<double, double> > sig;
TinyXPath::xpath_processor source_proc (node(), "sig");
const unsigned n_nodes = source_proc.u_compute_xpath_node_set();
for (unsigned i = 0; i != n_nodes; ++i)
{
TiXmlNode* s = source_proc.XNp_get_xpath_node (i);
const double level = TinyXPath::xpath_processor(s, "level/text()").d_compute_xpath();
const double freq = TinyXPath::xpath_processor(s, "freq/text()").d_compute_xpath();
sig.push_back (std::make_pair (freq, level));
}
return sig;
}
std::vector< std::pair<double, double> > signature3() const
{
std::vector< std::pair<double, double> > sig;
int i = 1;
while (TiXmlNode* s = TinyXPath::xpath_processor (node(),
("sig[" + boost::lexical_cast<std::string>(i++) + "]/*").c_str()).
XNp_get_xpath_node(0))
{
const double level = TinyXPath::xpath_processor(s, "level/text()").d_compute_xpath();
const double freq = TinyXPath::xpath_processor(s, "freq/text()").d_compute_xpath();
sig.push_back (std::make_pair (freq, level));
}
return sig;
}
As a secondary issue, if so, which XPath library should I be using?