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
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.
16 #include <libxml/xmlreader.h>
18 #if defined(LIBXML_READER_ENABLED) && defined(LIBXML_PATTERN_ENABLED) && defined(LIBXML_OUTPUT_ENABLED)
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.
30 extractFile(const char *filename
, const xmlChar
*pattern
) {
32 xmlTextReaderPtr reader
;
36 * build an xmlReader for that file
38 reader
= xmlReaderForFile(filename
, NULL
, 0);
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
);
52 ret
= xmlTextReaderRead(reader
);
55 fprintf(stderr
, "%s : failed to parse\n", filename
);
56 xmlFreeTextReader(reader
);
60 * get the resulting nodes
62 doc
= xmlTextReaderCurrentDoc(reader
);
66 xmlFreeTextReader(reader
);
68 fprintf(stderr
, "Unable to open %s\n", filename
);
74 int main(int argc
, char **argv
) {
75 const char *filename
= "test3.xml";
76 const char *pattern
= "preserved";
85 * this initialize the library and check potential ABI mismatches
86 * between the version it was compiled for and the actual shared
91 doc
= extractFile(filename
, (const xmlChar
*) pattern
);
96 xmlDocDump(stdout
, doc
);
98 * don't forget to free up the doc
105 * Cleanup function for the XML library.
109 * this is to debug memory for regression tests
117 fprintf(stderr
, "Reader, Pattern or output support not compiled in\n");