-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
testxml.c
129 lines (111 loc) · 2.8 KB
/
testxml.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "config.h"
#include <stdio.h>
#include <ctype.h>
#include "setup-xml.h"
int copy_line(const char **srcpp, char *buf, int maxlen)
{
const char *srcp;
char *dstp;
/* Skip leading whitespace */
srcp = *srcpp;
while ( *srcp && isspace(*srcp) ) {
++srcp;
}
/* Copy the line */
dstp = buf;
while ( *srcp && (*srcp != '\r') && (*srcp != '\n') ) {
if ( (dstp-buf) >= maxlen ) {
break;
}
*dstp++ = *srcp++;
}
/* Trim whitespace */
while ( (dstp > buf) && isspace(*dstp) ) {
--dstp;
}
*dstp = '\0';
/* Update line pointer */
*srcpp = srcp;
/* Return the length of the line */
return strlen(buf);
}
void PrefixLevel(int level)
{
int i;
for ( i=0; i<level; ++i ) {
printf(" ");
}
}
void ParseNode(xmlDocPtr doc, xmlNodePtr cur, int level)
{
const char *data;
char buf[BUFSIZ];
while ( cur ) {
if ( strcmp(cur->name, "option") != 0 ) {
xmlSetProp(cur, "checked", "true");
}
if ( ! xmlNodeIsText(cur) ) {
PrefixLevel(level);
printf("Parsing %s node at level %d { \n", cur->name, level);
data = xmlNodeListGetString(doc, XML_CHILDREN(cur), 1);
if ( data ) {
while ( copy_line(&data, buf, BUFSIZ) ) {
PrefixLevel(level);
printf(" Data: %s\n", buf);
}
}
if ( XML_CHILDREN(cur) ) {
ParseNode(doc, XML_CHILDREN(cur), level+1);
}
PrefixLevel(level);
printf("}\n");
}
cur = cur->next;
}
}
xmlNodePtr FindNode(xmlNodePtr node, const char *name)
{
while ( node ) {
/* Did we find the node? */
if ( strcmp(node->name, name) == 0 ) {
return(node);
}
/* Look through the children */
if ( XML_CHILDREN(node) ) {
xmlNodePtr found;
found = FindNode(XML_CHILDREN(node), name);
if ( found ) {
return(found);
}
}
/* Keep looking */
node = node->next;
}
return(NULL);
}
const char *GetNodeText(xmlDocPtr doc, xmlNodePtr node, const char *name)
{
const char *text;
text = NULL;
node = FindNode(node, name);
if ( node ) {
text = xmlNodeListGetString(doc, XML_CHILDREN(node), 1);
}
return(text);
}
int main(void)
{
xmlDocPtr doc;
xmlNodePtr cur;
doc = xmlParseFile("setup.xml");
if ( doc ) {
printf("Description: %s\n", GetNodeText(doc, XML_ROOT(doc), "desc"));
cur = doc->root;
if ( cur ) {
printf("Root node name: %s\n", cur->name);
ParseNode(doc, cur, 0);
}
}
xmlSaveFile("foo.xml", doc);
return 0;
}