3

私は自分自身で RapidXML ソースを調べ、いくつかの値を読み取ることができました。次に、それらを変更して XML ファイルに保存します。

ファイルの解析とポインタの設定

void SettingsHandler::getConfigFile() {
    pcSourceConfig = parsing->readFileInChar(CONF);

    cfg.parse<0>(pcSourceConfig);
}

XML からの値の読み取り

void SettingsHandler::getDefinitions() {    
    SettingsHandler::getConfigFile();
    stGeneral = cfg.first_node("settings")->value();
    /* stGeneral = 60 */
}

値の変更とファイルへの保存

void SettingsHandler::setDefinitions() {
    SettingsHandler::getConfigFile();

    stGeneral = "10";

    cfg.first_node("settings")->value(stGeneral.c_str());

    std::stringstream sStream;
    sStream << *cfg.first_node();

    std::ofstream ofFileToWrite;
    ofFileToWrite.open(CONF, std::ios::trunc);
    ofFileToWrite << "<?xml version=\"1.0\"?>\n" << sStream.str() << '\0';
    ofFileToWrite.close();
}

ファイルをバッファに読み込む

char* Parser::readFileInChar(const char* p_pccFile) {
    char* cpBuffer;
    size_t sSize;

    std::ifstream ifFileToRead;
    ifFileToRead.open(p_pccFile, std::ios::binary);
    sSize = Parser::getFileLength(&ifFileToRead);
    cpBuffer = new char[sSize];
    ifFileToRead.read( cpBuffer, sSize);
    ifFileToRead.close();

    return cpBuffer;
}

ただし、新しい値を保存することはできません。私のコードは、元のファイルを「60」の値で保存するだけで、「10」になるはずです。

Rgdsレイン

4

3 に答える 3

2

これはRapidXMLの落とし穴だと思います

parse_no_data_nodesフラグを追加してみてくださいcfg.parse<0>(pcSourceConfig)

于 2010-03-11T21:23:01.570 に答える
1

ノードに属性を追加するには、次のメソッドを使用します。このメソッドは、rapidxml からの文字列のメモリ割り当てを使用します。したがって、ドキュメントが存続している限り、rapidxml は文字列を処理します。詳細については、 http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1modifying_dom_treeを参照してください。

void setStringAttribute(
        xml_document<>& doc, xml_node<>* node,
        const string& attributeName, const string& attributeValue)
{
    // allocate memory assigned to document for attribute value
    char* rapidAttributeValue = doc.allocate_string(attributeValue.c_str());
    // search for the attribute at the given node
    xml_attribute<>* attr = node->first_attribute(attributeName.c_str());
    if (attr != 0) { // attribute already exists
        // only change value of existing attribute
        attr->value(rapidAttributeValue);
    } else { // attribute does not exist
        // allocate memory assigned to document for attribute name
        char* rapidAttributeName = doc.allocate_string(attributeName.c_str());
        // create new a new attribute with the given name and value
        attr = doc.allocate_attribute(rapidAttributeName, rapidAttributeValue);
        // append attribute to node
        node->append_attribute(attr);
    }
}
于 2011-08-14T18:47:28.250 に答える
1

出力ファイルが正しく開かれ、書き込みが成功したことを確実にテストする必要があります。最も単純には、次のようなものが必要です。

if ( ! ofFileToWrite << "<?xml version=\"1.0\"?>\n" 
       << sStream.str() << '\0' ) {
    throw "write failed";
}

'\0' ターミネータは必要ありませんが、害はないことに注意してください。

于 2010-02-06T10:15:52.197 に答える