windows 下libxml2比如xml文档中闭合标签有SpecificInformation和SpecModSpecMod两种闭合方式如何保留文档中标签闭合方式并打印xml文件内容保存在内容中
在使用 libxml2 库处理 XML 文档时,可以使用 xmlSaveFormatFileEnc() 函数来保存 XML 文件,并保留文档中标签闭合方式。具体步骤如下:
- 使用
xmlReadFile()函数读取 XML 文件,得到一个xmlDocPtr类型的文档对象。
xmlDocPtr doc = xmlReadFile("example.xml", NULL, 0);
-
对文档对象进行处理,比如修改节点内容、删除节点等。
-
使用
xmlSaveFormatFileEnc()函数保存修改后的 XML 文件。该函数的第一个参数是保存的文件名,第二个参数是文档对象,第三个参数是字符编码。第四个参数指定是否将 XML 文件格式化输出,即是否在标签之间添加空格和换行符。如果要保留文档中标签闭合方式,则需要将该参数设置为 1。
xmlSaveFormatFileEnc("example_out.xml", doc, "UTF-8", 1);
完整示例代码如下:
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main() {
// 读取 XML 文件
xmlDocPtr doc = xmlReadFile("example.xml", NULL, 0);
if (doc == NULL) {
printf("Failed to parse XML file.\n");
return 1;
}
// 对文档对象进行处理
xmlNodePtr root = xmlDocGetRootElement(doc);
xmlNodePtr node = root->children;
while (node) {
if (xmlStrcmp(node->name, (const xmlChar *)"SpecificInformation") == 0) {
// 修改 SpecificInformation 节点内容
xmlNodeSetContent(node, (const xmlChar *)"specific info");
} else if (xmlStrcmp(node->name, (const xmlChar *)"SpecMod") == 0) {
// 删除 SpecMod 节点
xmlUnlinkNode(node);
xmlFreeNode(node);
}
node = node->next;
}
// 保存修改后的 XML 文件
xmlSaveFormatFileEnc("example_out.xml", doc, "UTF-8", 1);
// 释放资源
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
运行该程序后,会在当前目录下生成一个名为 example_out.xml 的文件,其中包含修改后的 XML 内容,同时保留了文档中标签闭合方式
原文地址: https://www.cveoy.top/t/topic/faDz 著作权归作者所有。请勿转载和采集!