TinyXML2 не может подсчитать количество тегов

0

У меня есть 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

По сути, код говорит, что почему-то день == продукт. Что мне здесь не хватает?

Теги:
xml-parsing

1 ответ

3
Лучший ответ

Посмотрите на возвращаемое значение compare

Compare не возвращает bool, вместо этого он возвращает число:

  • отрицательный, если a <b
  • ноль, если a == b
  • положительный, если a> b

Поэтому в вашем случае он возвращает 0 потому что две строки равны, поэтому ваш if выполняется на неравных строках. использование

if (tag.compare(prod_id) == 0) {
  • 0
    ну только одно слово. #embarrassment

Ещё вопросы

Сообщество Overcoder
Наверх
Меню