我有一个类似以下的XML文件:
<transaction>
<day>20</day>
<month>2</month>
<year>2014</year>
<product>
<barcode>123456789012</barcode>
<type>Food</type>
<price>12</price>
<currency>gbp</currency>
<name>Oreo</name>
<quantity>10</quantity>
</product>
<product>
<barcode>123456789012</barcode>
<type>Food</type>
<price>12</price>
<currency>gbp</currency>
<name>Oreo</name>
<quantity>10</quantity>
</product>
现在我想使用TinyXML2解析它,并编写了以下代码:
int count = 0;
int product_count = 0;
std::string prod_id("product");
//Get first node inside the root node then start iterations from there
XMLNode* node = doc.FirstChild()->FirstChild();
for(node; node; node=node->NextSibling()){
std::cout << node->Value() << std::endl;
count++;
std::string tag( node->Value());
if(tag.compare(prod_id)){
std::cout << "Product found!" << std::endl;
product_count++;
}
}
std::cout << "There are " << count << " tags in total" << std::endl;
std::cout << "There are " << product_count << " products in total" << std::endl;
然而,我得到的输出如下:
day
Product found!
month
Product found!
year
Product found!
product
product
There are 5 tags in total
There are 3 products in total
本质上代码说出于某种原因,天==产品。我在这里缺少什么?
答案 0 :(得分:3)
查看compare
比较不会返回bool
,而是返回一个数字:
所以在你的情况下它返回0
因为两个字符串是相等的,所以你的if是在非相等的字符串上执行的。使用
if (tag.compare(prod_id) == 0) {