Qt6 XML R/W

MEMO
QtでXMLファイルを読み書きするサンプルです
mainwindow.cpp

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // XMLファイルを更新
    // 入力ファイルを開く
    QFile inputFile("input.xml");
    if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open input file.";
        return;
    }
    // 出力ファイルを開く
    QFile outputFile("output.xml");
    if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Failed to open output file.";
        inputFile.close();
        return;
    }
    // XMLリーダーとライターを作成
    QXmlStreamReader xmlReader(&inputFile);
    QXmlStreamWriter xmlWriter(&outputFile);
    xmlWriter.setAutoFormatting(true);

    // XMLファイルを読み込み、属性を変更して書き込む
    while (!xmlReader.atEnd()) {
        xmlReader.readNext();
        if (xmlReader.isStartElement()) {
            if (xmlReader.name().toString() == "target_element") { // 変更したい要素名に置き換える
                // 特定の属性の値を変更
                QString attributeValue = xmlReader.attributes().value("attribute_name").toString(); // 属性名を指定
                // ここでattributeValueを変更する
                // 新しい属性値を設定
                xmlWriter.writeStartElement(xmlReader.name().toString());
                // 他の属性を取得し、"attribute_name"を除外して書き込む
                QXmlStreamAttributes attributes = xmlReader.attributes();
                for (const auto& attribute : attributes) {
                    if (attribute.name().toString() == "attribute_name") {
                        xmlWriter.writeAttribute("attribute_name", "new_value"); // 新しい値を指定
                    } else {
                        xmlWriter.writeAttribute(attribute.name().toString(), attribute.value().toString());
                    }
                }
            } else if (xmlReader.name().toString() == "Status") { // <Status>タグの処理を追加
                // <Status>タグの内容をそのまま出力ファイルに書き込む
                xmlWriter.writeStartElement(xmlReader.name().toString());
                xmlWriter.writeAttributes(xmlReader.attributes());
            } else {
                // そのまま要素を書き込む
                xmlWriter.writeStartElement(xmlReader.name().toString());
                xmlWriter.writeAttributes(xmlReader.attributes());
            }
        } else if (xmlReader.isEndElement()) {
            xmlWriter.writeEndElement();
        } else {
            // その他のテキストやコメントなどを書き込む
            xmlWriter.writeCharacters(xmlReader.text().toString());
        }
    }
    // エラー処理
    if (xmlReader.hasError()) {
        qDebug() << "XML error: " << xmlReader.errorString();
    }
    // ファイルを閉じる
    inputFile.close();
    outputFile.close();
}