TinyXML2在C ++中的同一元素内解析数据

时间:2017-09-08 16:31:19

标签: c++ xml tinyxml

我有一个像这样的XML文件:

<Aircraft callsign="MS842" type="B703">
  <State>89220.4892904 52914.9322014 8229.6 0 0 4.36332312999 0 0 70.0 270.741736633 0</State>
  <AutoPilot>
    <Mode setpoint="174.89485525" type="MODE_SPD_CAS"/>
    <Mode setpoint="8229.6" type="MODE_ALT_HLD"/>
    <Mode setpoint="4.36332312999" type="MODE_HDG_SEL"/>
  </AutoPilot>
</Aircraft>

我需要解析子元素中的数据&#34; State&#34;。我需要的是来自该元素内特定位置的数据:

  1. 第一个数据:px = 89220.4892904
  2. 第二个数据:py = 52914.9322014
  3. 第6个数据:ph = 4.36332312999
  4. 其中px,py和ph是double类型的一些变量。

    如果我运行以下内容:

    TiXmlElement* subelement = 0;
    subelement = xmlac->FirstChildElement("State");
    std::cout << "Elem : " subelement[0] << endl;
    

    我得到以下内容:

    Elem : <State>89220.4892904 52914.9322014 8229.6 0 0 4.36332312999 0 0 70.0 270.741736633 0</State>
    

    有没有这样的方式:

    double px=0.0, py=0.0, ph=0.0;
    px = subelement[0][0]
    py = subelement[0][1]
    ph = subelement[0][2]
    

    做哪个工作? (我尝试了上面的代码。我得到了一个称为碎片错误的东西。)

    注:

    • 我在C ++方面的经验很少。如果概念过于繁琐,请指出您的答案/假设的来源
    • 语言:C ++
    • xml解析器:tinyxml

    感谢。

    编辑: 找到了解决方案。见下文

2 个答案:

答案 0 :(得分:1)

我建议使用GetText http://www.grinninglizard.com/tinyxmldocs/classTiXmlElement.html#b1436857d30ee2cdd0938c8437ff98d5函数从节点中提取数据字符串,然后使用stringstream来解析它

我确定你可以找到很多样本怎么做。这是一个简单的

#include<vector>
#include<sstream> 

std::vector<double> parse(const std::string& data)
{
    std::istringstream ss(data);
    double val;
    std::vector<double> res;
    while(ss >> val){
        res.push_back(val);
    }
    return res;
}

答案 1 :(得分:1)

我使用以下技术来获取字符串:

inline string getStringData(TiXmlElement* node)
{
  if (!node) return "";
  string ret;
  if (TiXmlNode* el = node->FirstChild()) {
    // Catch multirow data
    while (el) {
      if (el->Type() == TiXmlNode::TINYXML_TEXT)
        ret += el->ToText()->ValueStr();
      else
        return "";
      if ((el = el->NextSiblingElement())) ret += ' ';
    }
  }
  return ret;
}

以下方法将其分开:

TiXmlElement* subelement = 0;
subelement = xmlac->FirstChildElement("State");

// Get the initial position and heading
string mystr = getStringData(subelement);
std::istringstream ss(mystr);
double val;
int idx = 0;
std::vector<double> res;
while(ss >> val) {res.push_back(val);}
for (idx = 0; idx < 10; idx++){
    if ((idx == 0) || (idx == 1) || (idx == 5)) {
        std::cout << idx << " " << res[idx] << endl;
    }
}