0

我一直在寻找如何使用代码块和库 pugixml 解析 xml 文件,但我尝试了不同的方法,但它仍然不起作用。

我必须解析的 XML 包含在一个图(房屋)上,我在 C++ 中的程序是使用结构来表示这个图。

XML 文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<WATSON>
  <PHILIPS> 125 </PHILIPS>
  <PEREZ> 254 </PEREZ>
  <SANTOS> 222 </SANTOS>
</WATSON>
<PHILIPS>
    <CENTER> 121 </CENTER>
    <WATSON> 125 </WATSON>
    <SANTOS> 55 </SANTOS>
</PHILIPS>
<PEREZ>
    <WATSON> 254 </WATSON>
    <CENTER> 110 </CENTER>
</PEREZ>

ETC...

C ++中的代码:(重要部分:))

int main(){
    pugi::xml_document file;

    if (!file.load_file("Sample.xml")){
    cout << "Error loading file XML." << endl;
    system("PAUSE");
    return -1;
}
    pugi::xml_node node;
    getNodeInfo(node);
    cin.get();
    return 0;
}

void getNodeInfo(xml_node node){
    for (xml_node_iterator it = node.begin(); it != node.end(); ++it)
    {
        cout << it->name() << "\n--------\n";
        system("PAUSE");
        for (xml_attribute_iterator ait = it->attributes_begin(); ait != it->attributes_end(); ++ait)
    {
            cout << " " << ait->name() << ": " << ait->value() << endl;
    }
        cout << endl;
        for (xml_node_iterator sit = node.begin(); sit != node.end(); ++sit)
        {
            getNodeInfo(*sit);
    }
}
}

请告诉我,代码中的错误可能是什么?它总是进入 if 条件,我的意思是,它不加载文件。谢谢!

4

1 回答 1

0

我注意到几个错误。

首先,您将一个空节点发送到您的函数,因此它没有任何工作可做。您应该发送您加载的文件:

int main()
{
    pugi::xml_document file;

    xml_parse_result res;
    if(!(res = file.load_file("test.xml")))
    {
        cout << "Error loading file XML: " << res.description() << endl;
        system("PAUSE");
        return -1;
    }

    pugi::xml_node node; // you are sending an EMPTY node
    // getNodeInfo(node);

    // Send the file you just loaded instead
    getNodeInfo(file);

    cin.get();
    return 0;
}

此外,您的函数中正在进行的循环中有一个奇怪的循环。您已经在节点的子节点上循环,不需要对相同子节点的内部循环:

void getNodeInfo(xml_node node)
{
    for(xml_node_iterator it = node.begin(); it != node.end(); ++it)
    {
        cout << it->name() << "\n--------\n";
//      system("PAUSE");
        for(xml_attribute_iterator ait = it->attributes_begin();
        ait != it->attributes_end(); ++ait)
        {
            cout << " " << ait->name() << ": " << ait->value() << endl;
        }
        cout << endl;
// You are already in a loop for this node so no need for this
//      for(xml_node_iterator sit = node.begin(); sit != node.end(); ++sit)
//      {
//          getNodeInfo(*sit);
//      }

        // just use the iterator you are already looping over
        getNodeInfo(*it);
    }
}

最后,您的 XML 数据格式不正确。它需要一个像这样包罗万象的标签:

<?xml version="1.0" encoding="UTF-8"?>
<HOUSES>
    <WATSON att="att1">
        <PHILIPS> 125 </PHILIPS>
        <PEREZ> 254 </PEREZ>
        <SANTOS> 222 </SANTOS>
    </WATSON>
    <PHILIPS>
        <CENTER> 121 </CENTER>
        <WATSON> 125 </WATSON>
        <SANTOS> 55 </SANTOS>
    </PHILIPS>
    <PEREZ>
        <WATSON> 254 </WATSON>
        <CENTER> 110 </CENTER>
    </PEREZ>
</HOUSES>

希望有帮助。

于 2014-11-11T16:52:57.847 回答