reader3.c revision ffa7b7e2ba3841a80f9c5a69e89cc4b4e457840b
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 * usage: reader3
8 * test: reader3 > reader3.tmp ; diff reader3.tmp reader3.out ; rm reader3.tmp
9 * author: Daniel Veillard
10 * copy: see Copyright for the status of this software.
11 */
12
13#include <stdio.h>
14#include <libxml/xmlreader.h>
15
16/**
17 * streamFile:
18 * @filename: the file name to parse
19 *
20 * Parse and print information about an XML file.
21 *
22 * Returns the resulting doc with just the elements preserved.
23 */
24static xmlDocPtr
25extractFile(const char *filename, const xmlChar *pattern) {
26    xmlDocPtr doc;
27    xmlTextReaderPtr reader;
28    int ret;
29
30    /*
31     * build an xmlReader for that file
32     */
33    reader = xmlReaderForFile(filename, NULL, 0);
34    if (reader != NULL) {
35        /*
36	 * add the pattern to preserve
37	 */
38        if (xmlTextReaderPreservePattern(reader, pattern, NULL) < 0) {
39            fprintf(stderr, "%s : failed add preserve pattern %s\n",
40	            filename, (const char *) pattern);
41	}
42	/*
43	 * Parse and traverse the tree, collecting the nodes in the process
44	 */
45        ret = xmlTextReaderRead(reader);
46        while (ret == 1) {
47            ret = xmlTextReaderRead(reader);
48        }
49        if (ret != 0) {
50            fprintf(stderr, "%s : failed to parse\n", filename);
51	    xmlFreeTextReader(reader);
52	    return(NULL);
53        }
54	/*
55	 * get the resulting nodes
56	 */
57	doc = xmlTextReaderCurrentDoc(reader);
58	/*
59	 * Free up the reader
60	 */
61        xmlFreeTextReader(reader);
62    } else {
63        fprintf(stderr, "Unable to open %s\n", filename);
64	return(NULL);
65    }
66    return(doc);
67}
68
69int main(int argc, char **argv) {
70    const char *filename = "test3.xml";
71    const char *pattern = "preserved";
72    xmlDocPtr doc;
73
74    if (argc == 3) {
75        filename = argv[1];
76	pattern = argv[2];
77    }
78
79    /*
80     * this initialize the library and check potential ABI mismatches
81     * between the version it was compiled for and the actual shared
82     * library used.
83     */
84    LIBXML_TEST_VERSION
85
86    doc = extractFile(filename, (const xmlChar *) pattern);
87    if (doc != NULL) {
88        /*
89	 * ouptut the result.
90	 */
91        xmlDocDump(stdout, doc);
92	/*
93	 * don't forget to free up the doc
94	 */
95	xmlFreeDoc(doc);
96    }
97
98
99    /*
100     * Cleanup function for the XML library.
101     */
102    xmlCleanupParser();
103    return(0);
104}
105