c语言中如何将结构体和xml互相转换
时间: 2024-02-17 15:04:01 浏览: 229
在 C 语言中,可以使用 libxml2 库中提供的函数将结构体和 XML 互相转换。下面是一个简单的示例:
假设有一个结构体定义如下:
```c
typedef struct {
int id;
char name[20];
int age;
} Person;
```
我们可以将这个结构体转换为 XML 的格式,如下所示:
```xml
<Person>
<id>1</id>
<name>John</name>
<age>30</age>
</Person>
```
以下是将这个结构体转换为 XML 的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
typedef struct {
int id;
char name[20];
int age;
} Person;
xmlNodePtr create_person_node(xmlDocPtr doc, Person *person) {
xmlNodePtr node = xmlNewNode(NULL, "Person");
char buf[32];
xmlNewChild(node, NULL, "id", snprintf(buf, sizeof(buf), "%d", person->id), NULL);
xmlNewChild(node, NULL, "name", person->name, NULL);
xmlNewChild(node, NULL, "age", snprintf(buf, sizeof(buf), "%d", person->age), NULL);
return node;
}
int main() {
Person person = {1, "John", 30};
xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr root_node = xmlNewNode(NULL, "Root");
xmlDocSetRootElement(doc, root_node);
xmlNodePtr person_node = create_person_node(doc, &person);
xmlAddChild(root_node, person_node);
xmlChar *xml_buf = NULL;
int xml_size = 0;
xmlDocDumpFormatMemory(doc, &xml_buf, &xml_size, 1);
printf("XML:\n%s\n", (char *)xml_buf);
xmlFree(xml_buf);
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
```
而将 XML 转换为结构体的过程,则需要将读取到的 XML 节点的值依次赋值给结构体的成员变量。以下是将 XML 转换为结构体的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
typedef struct {
int id;
char name[20];
int age;
} Person;
Person *create_person_from_node(xmlNodePtr node) {
Person *person = (Person *)malloc(sizeof(Person));
memset(person, 0, sizeof(Person));
for (xmlNodePtr cur = node->children; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE) {
continue;
}
if (xmlStrcmp(cur->name, (const xmlChar *)"id") == 0) {
person->id = atoi((const char *)xmlNodeGetContent(cur));
} else if (xmlStrcmp(cur->name, (const xmlChar *)"name") == 0) {
strncpy(person->name, (const char *)xmlNodeGetContent(cur), sizeof(person->name) - 1);
} else if (xmlStrcmp(cur->name, (const xmlChar *)"age") == 0) {
person->age = atoi((const char *)xmlNodeGetContent(cur));
}
}
return person;
}
int main() {
const char *xml_str = "<Root><Person><id>1</id><name>John</name><age>30</age></Person></Root>";
xmlDocPtr doc = xmlReadMemory(xml_str, strlen(xml_str), "noname.xml", NULL, 0);
xmlNodePtr root_node = xmlDocGetRootElement(doc);
for (xmlNodePtr cur = root_node->children; cur != NULL; cur = cur->next) {
if (cur->type != XML_ELEMENT_NODE) {
continue;
}
Person *person = create_person_from_node(cur);
printf("Person: id=%d, name=%s, age=%d\n", person->id, person->name, person->age);
free(person);
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
```
以上是一个简单的将结构体和 XML 互相转换的示例,具体实现可以根据实际情况进行修改和扩展。
阅读全文