4

昨日は私の最初の試みでした。次の「new.xml」ファイルで変数「time」をキャッチしようとしています

<?xml version="1.0" standalone=no>
<main>
 <ToDo time="1">
  <Item priority="1"> Go to the <bold>Toy store!</bold></Item>
  <Item priority="2"> Do bills</Item>
 </ToDo>
 <ToDo time="2">
  <Item priority="1"> Go to the Second<bold>Toy store!</bold></Item>
 </ToDo>
</main>

これが私のコードです

TiXmlDocument doc("new.xml");
TiXmlNode * element=doc.FirstChild("main");
element=element->FirstChild("ToDo");
string temp=static_cast<TiXmlElement *>(element)->Attribute("time");

しかし、3行目と4行目から実行時エラーが発生しています。誰かがこの問題に光を当てることができますか?

4

3 に答える 3

2

ファイルの読み込みを忘れたようです。通常、私はこれらの線に沿って何かをします:

TiXmlDocument doc("document.xml");
bool loadOkay = doc.LoadFile(); // Error checking in case file is missing
if(loadOkay)
{
    TiXmlElement *pRoot = doc.RootElement();
    TiXmlElement *element = pRoot->FirstChildElement();
    while(element)
    {
        string value = firstChild->Value(); // In your example xml file this gives you ToDo
        string attribute = firstChild->Attribute("time"); //Gets you the time variable
        element = element->NextSiblingElement();
    }
}
else
{
    //Error conditions
} 

お役に立てれば

于 2010-11-12T17:55:33.633 に答える
0
#include "tinyXml/tinyxml.h"

const char MY_XML[] = "<?xml version='1.0' standalone=no><main> <ToDo time='1'>  <Item priority='1'> Go to the <bold>Toy store!</bold></Item>  <Item priority='2'> Do bills</Item> </ToDo> <ToDo time='2'>  <Item priority='1'> Go to the Second<bold>Toy store!</bold></Item> </ToDo></main>";

void main()
{
    TiXmlDocument doc;
    TiXmlHandle docHandle(&doc);

    const char * const the_xml = MY_XML;
    doc.Parse(MY_XML);

    TiXmlElement* xElement = NULL;
    xElement = docHandle.FirstChild("main").FirstChild("ToDo").ToElement();

    int element_time = -1;

    while(xElement)
    {
        if(xElement->QueryIntAttribute("time", (int*)&element_time) != TIXML_SUCCESS)
            throw;

        xElement = xElement->NextSiblingElement();
    }
}

それがどのように機能するかです。コンパイルおよびテスト済み。
ご覧のとおり、非常に安全なコードを作成しようとすると、(質問の)3行目で例外が発生します。テストを行わないと、「nullを指す」例外であるに違いありません。

TinyXmlのドキュメントにもあるように、私のスタイルをロードしてください: "docHandle.FirstChild(" main ")。FirstChild(" ToDo ")。ToElement();"。

それがあなたが理解するのに役立つことを願っています、それが明確でないならば私に知らせてください。ビザを受け入れます(:

于 2010-11-12T17:36:34.540 に答える
0

それは私だけですか、それともpugixmlバージョンの方がはるかに良く見えますか?

#include <iostream>
#include "pugixml.hpp"

using namespace std;
using namespace pugi;

int main()
{   
    xml_document doc;
    if (!doc.load_file("new.xml"))
    {
        cerr << "Could not load xml";
        return 1;
    }
    xml_node element = doc.child("main");
    element = element.child("ToDo");

    cout << "Time: " << element.attribute("time") << endl;
}

またnew.xml、次の代わりにエラーが発生しました:

<?xml version="1.0" standalone=no>

する必要があります

<?xml version="1.0" standalone="no"?>

コンパイルはただの問題でしたcl test.cpp pugixml.cpp

于 2010-11-12T18:03:34.347 に答える