[studxml-users] Fastest way to count the number of elements with a specific name or at a specific depth?

Thibault de COINCY decoincy.thibault at gmail.com
Thu Sep 8 09:32:44 EDT 2022


Hi

What is the fastest way to count the number of elements with a specific
name or at a specific depth?
I have an XML like this and I'm trying to count the number of brands:

<cars>
<brand attr=1>
<model attr=1>text1</model>
<model attr=4>text4</model>
...
<model attr=99>text99</model>
<model attr=100>text100</model>
</brand>
<brand attr=3>
<model attr=1>text1</model>
<model attr=5>text5</model>
...
<model attr=49>text49</model>
<model attr=50>text50</model>
</brand>
...
<brand attr=1000000>
<model attr=1>text1</model>
<model attr=2>text2</model>
...
<model attr=124>text124</model>
<model attr=125>text125</model>
</brand>
</cars>

I use something like this, but it is very slow:

int BrandCount = 0;
xml::parser parser(xml_stream, xml_path, xml::parser::receive_elements);
for (xml::parser::event_type event (parser.next()); event !=
xml::parser::eof; event = parser.next()){
if (event == xml::parser::start_element) {
if (parser.name = "brand") {++BrandCount;};
};
};

Is there a way to speed up the process?
Currently, the parser goes through every single element, is it possible to
skip elements that are not "brand"?
Given I'm not interested in getting the content of the elements but only
the count, is there a way to optimize the parser somehow?

Many thanks!!
Thibault


More information about the studxml-users mailing list