3

I'm aware there are several XML libaries out there, but unfortunately, I am unable to use them for a school project I am working on.

I have a program that created this XML file.

<theKey>
<theValue>23432</theValue>
</theKey>

What I am trying to do is parse out "23432" between the tags. However, there are random tags in the file so may not always on the second line from the top. Also, I don't know how many digits the number is between the tags.

Here is the code I developed so far. It is basic because I don't know what I can use that is part of the C++ language that will parse the value out. My hint, from me working with JAVA, is to use somethign from the "String" library but so far I am coming up short on what I can use.

Can anyone give me direction or a clue on what I can do/use? Thanks a lot.

Here is the code I developed so far:

#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::fstream;
using std::string;
using std::ifstream;


int main()
{
 ifstream inFile;
 inFile.open("theXML.xml");

 if (!inFile)
 {
 }

 string x;
 while (inFile >> x)
 {
  cout << x << endl;
 }

 inFile.close();

 system ( "PAUSE" );


 return 0;
}
4

4 に答える 4

7

任意の XML を解析するには、適切な XML パーサーが本当に必要です。言語のすべての文字モデルの隅と DTD 関連の隙間を含めると、解析はまったく単純ではなく、XML の任意のサブセットのみを理解するパーサーを作成するのはひどい間違いです。

現実の世界では、これを実装するために適切な XML パーサー ライブラリ以外を使用するのは間違っています。ライブラリを使用できず、プログラムの出力形式をより簡単に解析できる形式 (改行で区切られたキーと値のペアなど) に変更できない場合は、支持できない立場にあります。XML パーサーなしで XML を解析する必要がある学校のプロジェクトは、まったく見当違いです。

(まあ、プロジェクトの要点が C++ で XML パーサーを書くことでない限り。しかし、それは非常に残酷な割り当てになるでしょう。)

于 2010-02-08T23:24:10.113 に答える
4

コードの概要は次のとおりです (面倒な部分は演習として省略しています)。

std::string whole_file;

// TODO:  read your whole XML file into "whole_file"

std::size_t found = whole_file.find("<theValue>");

// TODO: ensure that the opening tag was actually found ...

std::string aux = whole_file.substr(found);
found = aux.find(">");

// TODO: ensure that the closing angle bracket was actually found ...

aux = aux.substr(found + 1);

std::size_t end_found = aux.find("</theValue>");

// TODO: ensure that the closing tag was actually found ...

std::string num_as_str = aux.substr(0, end_found); // "23432"

int the_num;

// TODO: convert "num_as_str" to int

もちろん、これは適切な XML パーサーではなく、問題を解決する迅速で汚いものです。

于 2010-02-08T23:47:20.037 に答える
2

少なくとも次の機能を作成する必要があります。

  • ノードがコンテナ ノードの場合
    • 要素 (始まりと終わり) と属性 (存在する場合) を特定/解析する
    • 子を再帰的に解析する
  • それ以外の場合、重要でない場合は、末尾および先頭の空白があればそれをトリミングしながら値を抽出します

は、、などのstd::string非常に多くの便利なメンバー関数を提供します。これらを関数で使用してみてください。findfind_first_ofsubstr

于 2010-02-08T23:03:33.760 に答える
2

C++ 標準ライブラリには、XML 解析機能はありません。これを自分で書きたい場合は、 std::geline() を見てデータを文字列に読み込むことをお勧めします (これには operator>> を使用しないでください)。次に std::string クラスの基本それを切り刻む substr() 関数のような機能。ただし、独自の XML パーサーを作成することは、基本的なものであっても簡単ではないことに注意してください。

于 2010-02-08T23:04:04.820 に答える