<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="CHILDREN">
<title>Harry.Potter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
解析:
1、 FILE *fp = fopen(xml_file, "r"); //打开xml文件,注意文件路径与文件打开方式
2、 mxml_node_t *tree = mxmlLoadFile(NULL, fp, MXML_TEXT_CALLBACK); //获取xml文件指针
fclose(fp); //此处可以关闭文件
3、mxml_node_t *book = mxmlFindElement(pRoot, pRoot,"book", "category", NULL,MXML_DESCEND);
//从父节点读取 book 节点
3.1 printf("book: %s\r\n",book->value.element.attrs[0].value); // 读取book 节点中第一个变量值
4、 mxml_node_t *title = mxmlFindElement(book,pRoot,"title",NULL,NULL,MXML_DESCEND); //获取字节点 title
4.1 printf("tirle :%s\r\n",title->child->value.text.string); //提取title文本内容
4.2
mxml_node_t *year = mxmlFindElement(book,pRoot,"year",NULL,NULL,MXML_DESCEND);
printf("year :%s\r\n",year->child->value.text.string); //取出第二个节点
5、 mxmlDelete(pRoot); //j结束
解析代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include "mxml.h"
// 打开并加载xml
mxml_node_t *open_xml(char xml_file[])
{
FILE *fp = fopen(xml_file, "r");
if(fp == NULL)
{
printf("Open the %s error!\n", xml_file);
return NULL;
}
else
{
printf("Open the %s success!\n", xml_file);
}
mxml_node_t *tree = mxmlLoadFile(NULL, fp, MXML_TEXT_CALLBACK);
fclose(fp);
if(tree == NULL)
{
printf("Load xml file error!\n");
return NULL;
}
else
{
printf("Load xml file succ!\n");
}
return tree;
}
// 关闭xml
void close_xml(mxml_node_t *tree)
{
if(tree != NULL)
{
mxmlDelete(tree);
}
}
int main(int argc, const char *argv[])
{
if(2 != argc)
{
fprintf(stdout, "Please statrt this program with %s xmlfilepath!", argv[0]);
return 1;
}
mxml_node_t *pRoot = open_xml(argv[1]);
if (pRoot == NULL)
{
printf("%s can not find element Node!\n",__FILE__,__LINE__);
return -1;
}
// 读取节点配置
mxml_node_t *book = mxmlFindElement(pRoot, pRoot,"book", "category", NULL,MXML_DESCEND);
book = mxmlFindElement(pRoot, pRoot,"book", "category", NULL,MXML_DESCEND);
if (book == NULL)
{
close_xml(pRoot);
printf("%s can not find element Node!\n",__FILE__,__LINE__);
return -1;
}
printf("book: %s\r\n",book->value.element.attrs[0].value);
mxml_node_t *title = mxmlFindElement(book,pRoot,"title",NULL,NULL,MXML_DESCEND);
printf("tirle :%s\r\n",title->child->value.text.string);
mxml_node_t *year = mxmlFindElement(book,pRoot,"year",NULL,NULL,MXML_DESCEND);
printf("year :%s\r\n",year->child->value.text.string);
mxmlDelete(pRoot);
return 0;
}