reader2.c revision b286d84b86ab85abb46a54f38e94de77c4db401c
1/** 2 * section: xmlReader 3 * synopsis: Parse and validate an XML file with an xmlReader 4 * purpose: Demonstrate the use of xmlReaderForFile() to parse an XML file 5 * validating the content in the process and activating options 6 * like entities substitution, and DTD attributes defaulting 7 * usage: reader2 <valid_xml_filename> 8 * test: reader2 test2.xml > reader1.tmp ; diff reader1.tmp reader1.res ; rm reader1.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 * processNode: 18 * @reader: the xmlReader 19 * 20 * Dump information about the current node 21 */ 22static void 23processNode(xmlTextReaderPtr reader) { 24 const xmlChar *name, *value; 25 26 name = xmlTextReaderConstName(reader); 27 if (name == NULL) 28 name = BAD_CAST "--"; 29 30 value = xmlTextReaderConstValue(reader); 31 32 printf("%d %d %s %d %d", 33 xmlTextReaderDepth(reader), 34 xmlTextReaderNodeType(reader), 35 name, 36 xmlTextReaderIsEmptyElement(reader), 37 xmlTextReaderHasValue(reader)); 38 if (value == NULL) 39 printf("\n"); 40 else { 41 if (xmlStrlen(value) > 40) 42 printf(" %.40s...\n", value); 43 else 44 printf(" %s\n", value); 45 } 46} 47 48/** 49 * streamFile: 50 * @filename: the file name to parse 51 * 52 * Parse, validate and print information about an XML file. 53 */ 54static void 55streamFile(const char *filename) { 56 xmlTextReaderPtr reader; 57 int ret; 58 59 60 /* 61 * Pass some special parsing options to activate DTD attribute defaulting, 62 * entities substitution and DTD validation 63 */ 64 reader = xmlReaderForFile(filename, NULL, 65 XML_PARSE_DTDATTR | /* default DTD attributes */ 66 XML_PARSE_NOENT | /* substitute entities */ 67 XML_PARSE_DTDVALID); /* validate with the DTD */ 68 if (reader != NULL) { 69 ret = xmlTextReaderRead(reader); 70 while (ret == 1) { 71 processNode(reader); 72 ret = xmlTextReaderRead(reader); 73 } 74 /* 75 * Once the document has been fully parsed check the validation results 76 */ 77 if (xmlTextReaderIsValid(reader) != 1) { 78 fprintf(stderr, "Document %s does not validate\n", filename); 79 } 80 xmlFreeTextReader(reader); 81 if (ret != 0) { 82 fprintf(stderr, "%s : failed to parse\n", filename); 83 } 84 } else { 85 fprintf(stderr, "Unable to open %s\n", filename); 86 } 87} 88 89int main(int argc, char **argv) { 90 if (argc != 2) 91 return(1); 92 93 /* 94 * this initialize the library and check potential ABI mismatches 95 * between the version it was compiled for and the actual shared 96 * library used. 97 */ 98 LIBXML_TEST_VERSION 99 100 streamFile(argv[1]); 101 102 /* 103 * Cleanup function for the XML library. 104 */ 105 xmlCleanupParser(); 106 return(0); 107} 108