【问题标题】:TinyXML2 cannot count number of tagsTinyXML2 无法计算标签数量
【发布时间】:2014-09-16 23:38:24
【问题描述】:

我有一个如下的 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

从本质上讲,代码出于某种原因表示 day == product。我在这里错过了什么?

【问题讨论】:

    标签: c++ xml xml-parsing


    【解决方案1】:

    compare的返回值

    Compare 不返回 bool,而是返回一个数字:

    • 如果 a 则为负
    • 如果 a == b 则为零
    • 如果 a > b 则为阳性

    因此,在您的情况下,它返回 0 因为两个字符串相等,因此您的 if 是在不相等的字符串上执行的。使用

    if (tag.compare(prod_id) == 0) {
    

    【讨论】:

    • 只有一个字。 #尴尬
    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 2011-01-03
    • 2016-01-03
    • 2023-03-16
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多