2010-05-11 103 views
16

我必須用C++解析XML文件。我正在研究併爲此找到RapidXml庫。如何解析RapidXML中的XML文件

我對doc.parse<0>(xml)有疑問。

可以xml是.xml文件還是它需要是stringchar *

如果只能採取stringchar *那麼我想我需要讀取整個文件並將其存儲在char數組中,並將其指針傳遞給該函數?

有沒有辦法直接使用文件,因爲我需要更改代碼中的XML文件。

如果在RapidXML中不可行,那麼請在C++中建議一些其他XML庫。

謝謝!

Ashd

+1

xml_document :: parse()的參數是包含xml的以零結尾的字符串。所以你只需要創建一個file2string函數。將文件讀入一個向量緩衝區,然後將&buffer [0]傳遞給parse()。 – anno 2010-05-30 03:04:43

+0

vtd-xml也有C++端口,與rapidXML相比,vtd-xml更符合,穩定和高效...... – 2011-01-02 22:34:36

回答

0

manual告訴我們:

功能xml_document ::解析

[...]根據給定的標誌解析零結尾的XML字符串 。

RapidXML讓葉片從文件中加載字符數據給你。將文件讀入緩衝區,例如建議使用anno,或者使用一些內存映射技術。 (但是請先查看parse_non_destructive標誌。)

7

新來C++自己...但我想分享一個解決方案。

YMMV!

喊出SiCrane這個thread: - 而只是一個載體代替「串」 ---(感謝安諾)

請評論並幫助我也學習!我很新的這

無論如何,這似乎有一個良好的開始工作:

#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 */ 


} 
+0

這很好,但只有'vector buffer'不會超出範圍:a快速和骯髒的方式來解決這個問題是通過添加'靜態'關鍵字向量,但我不認爲這是真的很乾淨。 請參閱:http://stackoverflow.com/questions/6363719/rapidxml-reading-from-file-what-is-wrong-here – FlipMcF 2011-07-23 01:45:55

2

我們通常從磁盤讀取的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]); 

對於一個完整的源代碼的檢查:

Read a line from xml file using C++

+0

由於調整矢量大小,這太慢了。與Superfly Jon的回答相比,它要快得多。 – 2015-05-15 15:54:25

26

RapidXml提供了一個類來爲你做這件事,rapidxml::filerapidxml_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()); 
... 
} 

注意,xmlFile對象現在包含了所有XML,這意味着,一旦超出範圍和被破壞doc變量不再安全使用的數據。如果你在一個函數內部調用分析,你必須以某種方式保留內存中的對象(全局變量,新的等),以便該文檔保持有效。