You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TinyXML2 C++修改指定属性的XML标签内容?

Complete TinyXML2 Workflow for XML Modification

Hey there! Let's walk through the full process to get your XML modification task done with TinyXML2. You already have the file loading part down, so let's build on that step by step.

Step 1: Load the XML File (With Error Checking)

First, let's beef up your existing loading code with error handling to catch issues early:

#include "tinyxml2.h"
using namespace tinyxml2;

int main() {
    XMLDocument doc;
    XMLError loadResult = doc.LoadFile("file.xml");
    if (loadResult != XML_SUCCESS) {
        printf("Failed to load XML file: %s\n", doc.ErrorName());
        return 1;
    }

Step 2: Grab the Root Element

Every valid XML document has a root element—let's retrieve it and make sure it exists:

XMLElement* root = doc.RootElement();
    if (!root) {
        printf("XML file has no root element.\n");
        return 1;
    }

Step 3: Find and Modify the Target Element

Now we'll loop through all <dog> elements, check for the one with colour="brown", and update its text content:

// Iterate through all <dog> elements in the document
    XMLElement* dogElement = root->FirstChildElement("dog");
    while (dogElement != nullptr) {
        // Get the value of the "colour" attribute
        const char* colourAttr = dogElement->Attribute("colour");
        
        // Check if the attribute exists and matches "brown"
        if (colourAttr && strcmp(colourAttr, "brown") == 0) {
            // Update the element's text content
            dogElement->SetText("Waow!");
            printf("Successfully modified the brown dog's text.\n");
            
            // Uncomment this line if you only need to modify the first matching element
            // break;
        }
        
        // Move to the next <dog> element
        dogElement = dogElement->NextSiblingElement("dog");
    }

Step 4: Save the Modified XML

Don't forget to write your changes back to the file:

XMLError saveResult = doc.SaveFile("file.xml");
    if (saveResult != XML_SUCCESS) {
        printf("Failed to save XML file: %s\n", doc.ErrorName());
        return 1;
    }

    printf("XML file updated and saved successfully!\n");
    return 0;
}

Key Notes:

  • Error Checking: The added checks help you debug issues like missing files or invalid XML structure.
  • Multiple Matches: The code above modifies all <dog colour="brown"> elements. If you only want to change the first one, uncomment the break; line inside the if block.
  • Attribute Comparison: We use strcmp instead of == because Attribute() returns a C-style string—== would compare memory addresses instead of the actual text.

内容的提问来源于stack exchange,提问作者Danish Singh Sethi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:32:43