0

C++ を使用して、基本的な txt ファイルから XML ファイルにデータをフィードしようとしています。タグの書き方は理解できましたが、ハードコーディングから動的リストの追加に切り替えるにはどうすればよいですか? 私はこのクラスを使って私を助けています。

#include <fstream>
#include <iostream>
#include <string>
#include "xmlwriter.h"

using namespace std;
using namespace xmlw;

int main()
{
  ofstream f("output.xml");
  XmlStream xml(f);

  xml << prolog() // write XML file declaration

      << tag("blocks") 
          << attr("version") << "1"
          << attr("app") << "Snap! 4.0, http://snap.berkeley.edu"

            << tag("block-definition") 
              << attr("category") << "sensing"
              << attr("type") << "command"
              << attr("s") << "data reporter"

            << tag("header") << endtag()
            << tag("code") << endtag()
            << tag("inputs") << endtag()

            << tag("script") 
              << tag("block") 
                << attr("s") << "doSetVar"
                    << tag("l") 
                      << chardata() << "datalist" 
                    << endtag()

                  << tag("block") 
                    << attr("s") << "reportNewList"

                    << tag("list")

                    insertdata();


      << endtag("block-definition"); // close all tags up to specified

  // look: I didn't close "sample-tag", it will be closed in XmlStream destructor

  return 0;
}

void insertdata(){
  string line;
  ifstream myfile ("DATALOG.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      << tag("l") 
      << chardata() << line 
      << endtag()
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
}
4

1 に答える 1

0

この出力を insertdata() で xml オブジェクトに送信する必要があります。

  << tag("l") 
  << chardata() << line 
  << endtag()

これを行う 1 つの方法は、パラメーターとして xml への参照を渡すことです。

void insertdata(XmlStream &x) {
    ...
    x << tag("l") 
    << chardata() << line 
    << endtag();
    ...

次に、main() で適切に呼び出します。

    ...
    << tag("list");

    insertdata(xml);

    xml << endtag("block-definition"); // close all tags up to specified
于 2014-12-06T18:07:28.460 に答える