xml文件MFC解析

该代码示例展示了一个C++程序,它使用TinyXML2库解析XML文件,从中提取LED设备的信息(如CCD,启用状态,标题和通道)以及通信设置(如通讯编号,波特率,数据位,停止位,奇偶校验和流控)。程序首先加载XML文件,然后遍历找到的元素,将数据存储在LedInfo结构体的向量中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include "tinyxml2.h"

using namespace std;
using namespace tinyxml2;

struct LedInfo {
    int CCD;
    bool enable;
    string title;
    int chn;
};

int main() {
    vector<LedInfo> ledList;

    XMLDocument doc;
    doc.LoadFile("example.xml");

    XMLElement* root = doc.FirstChildElement("LedList");
    if (root == nullptr) {
        cout << "Error: no LedList element found in XML file." << endl;
        return 1;
    }

    // Parse communication settings
    XMLElement* commSet = root->FirstChildElement("CommSet");
    if (commSet != nullptr) {
        int commNum = commSet->IntAttribute("CommNum", 0);
        int rate = commSet->IntAttribute("rate", 0);
        int data = commSet->IntAttribute("data", 0);
        int stopbit = commSet->IntAttribute("stopbit", 0);
        const char* parityStr = commSet->Attribute("parity");
        bool parity = (parityStr != nullptr) && (strcmp(parityStr, "Yes") == 0);
        const char* flowStr = commSet->Attribute("flow");
        bool flow = (flowStr != nullptr) && (strcmp(flowStr, "Yes") == 0);

        // Do something with the communication settings...
        cout << "Communication settings: CommNum=" << commNum << ", rate=" << rate
            << ", data=" << data << ", stopbit=" << stopbit << ", parity=" << parity
            << ", flow=" << flow << endl;
    }

    // Parse Led elements
    for (XMLElement* led = root->FirstChildElement(); led != nullptr; led = led->NextSiblingElement()) {
        if (strcmp(led->Name(), "CommSet") == 0) {
            // Skip CommSet element, since we've already parsed it
            continue;
        }

        LedInfo info;
        info.CCD = led->IntAttribute("CCD", 0);
        info.enable = led->FirstChildElement("enable")->BoolText();
        info.title = led->FirstChildElement("title")->GetText();
        info.chn = led->FirstChildElement("chn")->IntText();

        ledList.push_back(info);
    }

    // Do something with the Led information
    for (const auto& led : ledList) {
        cout << "Led CCD=" << led.CCD << ", enable=" << led.enable << ", title=" << led.title
            << ", chn=" << led.chn << endl;
    }

    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值