21

C++ で XML ファイルを解析する必要があります。私は調査していて、このための RapidXml ライブラリを見つけました。

について疑問がありdoc.parse<0>(xml)ます。

.xml ファイルにすることができますか、それとも またはxmlである必要がありますstringchar *?

または、ファイル全体を読み取って char 配列に格納し、そのポインタを関数に渡す必要があると思いますかstring?char *

コード内の XML ファイルも変更する必要があるため、ファイルを直接使用する方法はありますか。

RapidXml でそれが不可能な場合は、C++ の他の XML ライブラリを提案してください。

ありがとう!!!

アシュド

4

4 に答える 4

34

RapidXml には、これを行うためのクラスがファイルに含まrapidxml::fileれていrapidxml_utils.hppます。何かのようなもの:

#include "rapidxml_utils.hpp"

int main() {
    rapidxml::file<> xmlFile("somefile.xml"); // Default template is char
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());
...
}

オブジェクトには XML のすべてのデータが含まれていることに注意してください。つまり、xmlFileオブジェクトがスコープ外に出て破棄されると、doc 変数は安全に使用できなくなります。関数内で parse を呼び出す場合xmlFile、doc が有効なままになるように、オブジェクト (グローバル変数、new など) を何らかの方法でメモリに保持する必要があります。

于 2013-01-25T15:03:01.503 に答える
9

私自身C++は初めてですが、解決策を共有したかったのです。

YMMV!

このスレッドで SiCrane に声をかけてください: -- そして「文字列」をベクトルに置き換えるだけです ---

コメントして、私も学ぶのを手伝ってください!私はこれに非常に慣れていません

とにかく、これは良いスタートを切るようです:

#include <iostream>
#include <fstream>
#include <vector>

#include "../../rapidxml/rapidxml.hpp"

using namespace std;

int main(){
   ifstream myfile("sampleconfig.xml");
   rapidxml::xml_document<> doc;

   /* "Read file into vector<char>"  See linked thread above*/
   vector<char> buffer((istreambuf_iterator<char>(myfile)), istreambuf_iterator<char>( ));

   buffer.push_back('\0');

   cout<<&buffer[0]<<endl; /*test the buffer */

   doc.parse<0>(&buffer[0]); 

   cout << "Name of my first node is: " << doc.first_node()->name() << "\n";  /*test the xml_document */


}
于 2011-05-15T17:18:50.680 に答える
1

通常、XML をディスクから に読み取り、以下に示すようstd::stringにその安全なコピーを に作成します。std::vector<char>

string input_xml;
string line;
ifstream in("demo.xml");

// read file into input_xml
while(getline(in,line))
    input_xml += line;

// make a safe-to-modify copy of input_xml
// (you should never modify the contents of an std::string directly)
vector<char> xml_copy(input_xml.begin(), input_xml.end());
xml_copy.push_back('\0');

// only use xml_copy from here on!
xml_document<> doc;
// we are choosing to parse the XML declaration
// parse_no_data_nodes prevents RapidXML from using the somewhat surprising
// behavior of having both values and data nodes, and having data nodes take
// precedence over values when printing
// >>> note that this will skip parsing of CDATA nodes <<<
doc.parse<parse_declaration_node | parse_no_data_nodes>(&xml_copy[0]);

完全なソース コード チェックの場合:

C++ を使用して xml ファイルから行を読み取る

于 2011-06-14T18:50:19.713 に答える
0

マニュアルには次のように書かれています。

関数 xml_document::parse

[...] 指定されたフラグに従って、ゼロで終わる XML 文字列を解析します。

RapidXML では、ファイルからの文字データのロードはユーザーに任されています。annoが提案したようにファイルをバッファに読み込むか、代わりにメモリマッピング技術を使用してください。(ただし、parse_non_destructive最初にフラグを調べてください。)

于 2010-09-13T12:34:06.053 に答える