7

次の XML ファイルがあります。

<xml version="1.0" encoding="utf-8"?>
<データ>
    <パラメータ1>1</パラメータ1>
</データ>

新しいノード Parameter2="2" を Data ノードに追加したいと考えています。このコードは機能しません。保存されたファイルにはまだパラメーターが 1 つしか含まれていません。

    boost::property_tree::ptree ツリー;
    boost::property_tree::ptree dataTree;

    read_xml("test.xml", ツリー);
    dataTree = tree.get_child("データ");
    dataTree.put("パラメータ2", "2");

    boost::property_tree::xml_writer_settings w(' ', 4);
    write_xml("test.xml", ツリー, std::locale(), w);

dataTree.put の後に次の 2 行を追加すると、正しい結果が得られます。

    ツリー.クリア();
    tree.add_child("データ", dataTree);

より複雑なツリー構造で問題が発生するため、このソリューションは好きではありません。子ノードを削除/追加せずにプロパティ ツリーを更新することはできますか?

4

1 に答える 1

10

あなたのコードはほぼ正しいです。これが子ノードを更新する正しい方法です。

ただし、小さなバグがあります。次のように入力します。

dataTree = tree.get_child("Data");

「子」のコピーをdataTreeに割り当てます。したがって、次の行は階層ではなくコピーを参照します。あなたは書くべきです:

boost::property_tree::ptree &dataTree = tree.get_child("Data");

したがって、子への参照を取得します。

完全な例は次のとおりです。

  using namespace boost::property_tree;
  ptree tree;

  read_xml("data.xml", tree);
  ptree &dataTree = tree.get_child("Data");
  dataTree.put("Parameter2", "2");

  xml_writer_settings<char> w(' ', 4);
  write_xml("test.xml", tree, std::locale(), w);
于 2010-07-21T21:46:17.897 に答える