C ++:解析XML文件(MXML库)时出现问题

时间:2010-10-15 01:35:14

标签: c++ xml xml-parsing mini-xml

我遇到以下代码的问题。

它使用Mini-XML库从xml文件中提取元素。

它编译并运行正常,除了它无法获取最后一个“radius元素”,而是返回NULL(如果我不检查子节点是否为NULL,它会崩溃)。

//Start loading <ssys> elements
mxml_node_t *node; //temporary node to save
mxml_node_t *subnode; //temporary subnode to save
mxml_node_t *subnode2; //another temporary subnode to save
const char* name_tmp; //Temporary string for names of ssys
//Load first ssys
node = mxmlFindElement(Systems_elem, tree, "ssys", NULL, NULL, MXML_DESCEND);
cout << "Node 1 pointer: " << node<<endl<<endl;
//Start loading the rest of the ssys elements (but fail if first element is NULL)
int i = 1;
do {
    //Load node into vector of pointers
    ssys_elem.push_back(node);
    //Get name attribute
    name_tmp = mxmlElementGetAttr(node, "name");
    ssys_name.push_back(name_tmp);
    //load next ssys
    node = mxmlFindElement(node, tree, "ssys", NULL, NULL, MXML_NO_DESCEND);
    cout << "Node: " << node<<endl<<endl;
    cout<<"Name: " <<name_tmp<<endl<<endl;
    //Descend to radius element
    subnode = mxmlFindElement(node, tree, "radius", NULL, NULL, MXML_DESCEND);
    //
    if(subnode != NULL){
        cout <<subnode->child->value.text.string<<endl<<endl; <--Trouble Here
    }
   i++;
}
while (node != NULL);

}

以下是相关XML文件的一部分:

 <ssys name="Zylex">
  <general>
   <radius>3500.000000</radius> <-- I am trying to get "3500.000000"
   <stars>400</stars>
   <asteroids>0</asteroids>
   <interference>300.000000</interference>
   <nebula volatility="0.000000">250.000000</nebula>
  </general>
  <pos>
   <x>438.000000</x>
   <y>-34.000000</y>
  </pos>
  <assets/>
  <jumps>
   <jump target="Arcanis">
    <pos x="-3418.937501" y="-748.910119"/>
    <radius>200.000000</radius>
    <flags>
     <autopos/>
    </flags>
   </jump>
   <jump target="Doeston">
    <pos x="2991.156265" y="1817.411401"/>
    <radius>200.000000</radius>
    <flags>
     <autopos/>
    </flags>
   </jump>
  </jumps>
 </ssys>
</Systems>

此代码有什么问题?

1 个答案:

答案 0 :(得分:1)

嗯,我猜你在谈论Mini-XML,老实说我没有经验。我所看到的是,你的迭代器比你的名字领先一步。我想你想要更像的东西:

node = mxmlFindElement(Systems_elem, tree, "ssys", NULL, NULL, MXML_DESCEND);
while (node) {
    ssys_elem.push_back(node);
    name_tmp = mxmlElementGetAttr(node, "name");
    ssys_name.push_back(name_tmp);

    cout << "Node: " << node << endl << endl;
    if (name_tmp) {
        cout << "Name: " << name_tmp << endl << endl;
    }

    // Descend to radius element
    subnode = mxmlFindElement(node, tree, "radius", NULL, NULL, MXML_DESCEND);
    if (subnode != NULL){
        cout << subnode->child->value.text.string << endl << endl; <--Trouble Here
    }

    // iterate at the end!
    node = mxmlFindElement(node, tree, "ssys", NULL, NULL, MXML_NO_DESCEND);
}

总的来说,永远不要相信你有完善的XML。即使您认为应该有孩子,也要检查NULL。希望有所帮助。