-
Notifications
You must be signed in to change notification settings - Fork 50
/
xpath-test.c
126 lines (102 loc) · 2.47 KB
/
xpath-test.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
/*
* Small test app for our XPATH routines
*
* Copyright (C) 2010-2012 Olaf Kirch <[email protected]>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <getopt.h>
#include <wicked/netinfo.h>
#include <wicked/xpath.h>
#include <wicked/logging.h>
enum {
OPT_DEBUG,
OPT_REFERENCE,
};
static struct option options[] = {
{ "debug", required_argument, NULL, OPT_DEBUG },
{ "reference", required_argument, NULL, OPT_REFERENCE },
{ NULL }
};
int
main(int argc, char **argv)
{
const char *opt_reference = NULL;
const char *expression = NULL, *filename = "-";
xml_document_t *doc;
xml_node_t *refnode;
xpath_enode_t *enode;
xpath_result_t *result;
int c;
while ((c = getopt_long(argc, argv, "", options, NULL)) != EOF) {
switch (c) {
default:
usage:
fprintf(stderr,
"./xpath-test [--reference <expression>] <expression> [filename]\n"
);
return 1;
case OPT_DEBUG:
if (ni_enable_debug(optarg) < 0) {
fprintf(stderr, "Bad debug facility \"%s\"\n", optarg);
return 1;
}
break;
case OPT_REFERENCE:
opt_reference = optarg;
break;
}
}
if (optind >= argc)
goto usage;
expression = argv[optind++];
if (optind < argc)
filename = argv[optind++];
if (optind < argc)
goto usage;
doc = xml_document_read(filename);
if (!doc) {
fprintf(stderr, "Error parsing XML document %s\n", filename);
return 1;
}
refnode = doc->root;
if (opt_reference) {
enode = xpath_expression_parse(opt_reference);
if (!enode) {
fprintf(stderr, "Error parsing XPATH expression %s\n", opt_reference);
return 1;
}
result = xpath_expression_eval(enode, doc->root);
if (!result) {
fprintf(stderr, "Error evaluating XPATH expression\n");
return 1;
}
if (result->type != XPATH_ELEMENT) {
fprintf(stderr, "Failed to look up reference node - returned non-element result\n");
return 1;
}
if (result->count == 0) {
fprintf(stderr, "Failed to look up reference node - returned empty list\n");
return 1;
}
refnode = result->node[0].value.node;
xpath_result_free(result);
xpath_expression_free(enode);
}
enode = xpath_expression_parse(expression);
if (!enode) {
fprintf(stderr, "Error parsing XPATH expression %s\n", expression);
return 1;
}
result = xpath_expression_eval(enode, refnode);
if (!result) {
fprintf(stderr, "Error evaluating XPATH expression\n");
return 1;
}
xpath_result_print(result, stdout);
xpath_result_free(result);
xpath_expression_free(enode);
return 0;
}