libxml2 2.9.1 clean sources
[tomato.git] / release / src / router / libxml2 / doc / examples / reader3.c
blob3eeb61fecff62a732c5ba86a6a3b43eddfef410f
1 /**
2 * section: xmlReader
3 * synopsis: Show how to extract subdocuments with xmlReader
4 * purpose: Demonstrate the use of xmlTextReaderPreservePattern()
5 * to parse an XML file with the xmlReader while collecting
6 * only some subparts of the document.
7 * (Note that the XMLReader functions require libxml2 version later
8 * than 2.6.)
9 * usage: reader3
10 * test: reader3 > reader3.tmp && diff reader3.tmp $(srcdir)/reader3.res
11 * author: Daniel Veillard
12 * copy: see Copyright for the status of this software.
15 #include <stdio.h>
16 #include <libxml/xmlreader.h>
18 #if defined(LIBXML_READER_ENABLED) && defined(LIBXML_PATTERN_ENABLED) && defined(LIBXML_OUTPUT_ENABLED)
21 /**
22 * streamFile:
23 * @filename: the file name to parse
25 * Parse and print information about an XML file.
27 * Returns the resulting doc with just the elements preserved.
29 static xmlDocPtr
30 extractFile(const char *filename, const xmlChar *pattern) {
31 xmlDocPtr doc;
32 xmlTextReaderPtr reader;
33 int ret;
36 * build an xmlReader for that file
38 reader = xmlReaderForFile(filename, NULL, 0);
39 if (reader != NULL) {
41 * add the pattern to preserve
43 if (xmlTextReaderPreservePattern(reader, pattern, NULL) < 0) {
44 fprintf(stderr, "%s : failed add preserve pattern %s\n",
45 filename, (const char *) pattern);
48 * Parse and traverse the tree, collecting the nodes in the process
50 ret = xmlTextReaderRead(reader);
51 while (ret == 1) {
52 ret = xmlTextReaderRead(reader);
54 if (ret != 0) {
55 fprintf(stderr, "%s : failed to parse\n", filename);
56 xmlFreeTextReader(reader);
57 return(NULL);
60 * get the resulting nodes
62 doc = xmlTextReaderCurrentDoc(reader);
64 * Free up the reader
66 xmlFreeTextReader(reader);
67 } else {
68 fprintf(stderr, "Unable to open %s\n", filename);
69 return(NULL);
71 return(doc);
74 int main(int argc, char **argv) {
75 const char *filename = "test3.xml";
76 const char *pattern = "preserved";
77 xmlDocPtr doc;
79 if (argc == 3) {
80 filename = argv[1];
81 pattern = argv[2];
85 * this initialize the library and check potential ABI mismatches
86 * between the version it was compiled for and the actual shared
87 * library used.
89 LIBXML_TEST_VERSION
91 doc = extractFile(filename, (const xmlChar *) pattern);
92 if (doc != NULL) {
94 * ouptut the result.
96 xmlDocDump(stdout, doc);
98 * don't forget to free up the doc
100 xmlFreeDoc(doc);
105 * Cleanup function for the XML library.
107 xmlCleanupParser();
109 * this is to debug memory for regression tests
111 xmlMemoryDump();
112 return(0);
115 #else
116 int main(void) {
117 fprintf(stderr, "Reader, Pattern or output support not compiled in\n");
118 exit(1);
120 #endif