读书人

怎么定义一种数据结构来存储xml文件中

发布时间: 2013-01-25 15:55:29 作者: rapoo

如何定义一种数据结构来存储xml文件中的每个节点
问题如题,
xml文件例子如下
<?xml version="1.0" encoding="GBK" ?>
- <breakfast_menu>
- <food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
- <food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
- <food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
- <food>
<name>French Toast</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
- <food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>

上面是简单的一种情况,假如每个节点的格式不同,有该怎么做?求大神!
[解决办法]
xml是字符串,如果要存所有的节点内容,使用字符串是肯定行的。
[解决办法]
节点是XML中最重要的元素,xmlNode代表XML文档中的一个节点,实现为一个struct,此结构内容很丰富也很重要,其定义在tree.h中,具体说明如下:

typedef struct _xmlNode xmlNode;

typedef xmlNode *xmlNodePtr;

struct _xmlNode {

void *_private;/* application data */

xmlElementType type; /* type number, must be second ! */

const xmlChar *name; /* the name of the node, or the entity */

struct _xmlNode *children; /* parent->childs link */

struct _xmlNode *last; /* last child link */

struct _xmlNode *parent;/* child->parent link */

struct _xmlNode *next; /* next sibling link */

struct _xmlNode *prev; /* previous sibling link */



struct _xmlDoc *doc;/* the containing document */

/* End of common part */

xmlNs *ns; /* pointer to the associated namespace */

xmlChar *content; /* the content */

struct _xmlAttr *properties;/* properties list */

xmlNs *nsDef; /* namespace definitions on this node */

void *psvi;/* for type/PSVI informations */

unsigned short line; /* line number */

unsigned short extra; /* extra data for XPath/XSLT */

};

可以看到,节点之间是以链表和树两种方式同时组织起来的,next和prev指针可以组成链表,而parent和children可以组织为树。同时此结构还有以下重要成员:

? content:节点中的文字内容。

? doc:节点所属文档。

? name:节点名字。

? ns:节点的名字空间。

? properties:节点属性列表。

XML文档的操作其根本原理就是在节点之间移动、查询节点的各项信息,并进行增加、删除、修改等操作。

xmlDocSetRootElement函数可以将一个节点设置为某个文档的根节点,这是将文档与节点连接起来的重要手段,当有了根结点以后,所有子节点就可以依次连接上根节点,从而组织成为一个XML树。

读书人网 >XML SOAP

热点推荐