写一段C++源代码读以下XML文件的内容:<ModbusTcpConfig> <ConnectTion IpAddr="192.168.1.2" Port="502"> </ConnectTion> </ModbusTcpConfig>
时间: 2023-12-11 10:05:53 浏览: 35
以下是示例代码,可以读取上述XML文件内容:
```c
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main() {
xmlDocPtr doc;
xmlNodePtr root, connection;
xmlChar *ip, *port;
// 打开XML文件并解析
doc = xmlParseFile("config.xml");
if (doc == NULL) {
fprintf(stderr, "Failed to parse XML file.\n");
return 1;
}
// 获取根节点
root = xmlDocGetRootElement(doc);
if (root == NULL) {
fprintf(stderr, "Empty document.\n");
xmlFreeDoc(doc);
return 1;
}
// 查找 Connection 节点
connection = root->children;
while (connection != NULL) {
if (xmlStrcmp(connection->name, (const xmlChar *)"ConnectTion") == 0) {
break;
}
connection = connection->next;
}
// 获取 Connection 节点的属性值
if (connection != NULL) {
ip = xmlGetProp(connection, (const xmlChar *)"IpAddr");
port = xmlGetProp(connection, (const xmlChar *)"Port");
printf("IP: %s\n", ip);
printf("Port: %s\n", port);
} else {
fprintf(stderr, "Connection node not found.\n");
}
// 释放资源
xmlFree(ip);
xmlFree(port);
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
```
注意,需要安装 `libxml2` 库,并链接 `-lxml2`。