I want to validate XML files against an XSD on iOS. The documentations alludes to using NSXMLDocument to do this, but its not available on iOS =(. Are there any light weight alternatives to do this on iOS?
Asked
Active
Viewed 2,233 times
3 Answers
3
I ended up using the validation facilities in libxml2 since its a library already included in iOS. Following this sample code
#include <libxml/parser.h>
#include <libxml/xmlschemas.h>
int is_valid(const xmlDocPtr doc, const char *schema_filename)
{
xmlDocPtr schema_doc = xmlReadFile(schema_filename, NULL, XML_PARSE_NONET);
if (schema_doc == NULL) {
/* the schema cannot be loaded or is not well-formed */
return -1;
}
xmlSchemaParserCtxtPtr parser_ctxt = xmlSchemaNewDocParserCtxt(schema_doc);
if (parser_ctxt == NULL) {
/* unable to create a parser context for the schema */
xmlFreeDoc(schema_doc);
return -2;
}
xmlSchemaPtr schema = xmlSchemaParse(parser_ctxt);
if (schema == NULL) {
/* the schema itself is not valid */
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
return -3;
}
xmlSchemaValidCtxtPtr valid_ctxt = xmlSchemaNewValidCtxt(schema);
if (valid_ctxt == NULL) {
/* unable to create a validation context for the schema */
xmlSchemaFree(schema);
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
return -4;
}
int is_valid = (xmlSchemaValidateDoc(valid_ctxt, doc) == 0);
xmlSchemaFreeValidCtxt(valid_ctxt);
xmlSchemaFree(schema);
xmlSchemaFreeParserCtxt(parser_ctxt);
xmlFreeDoc(schema_doc);
/* force the return value to be non-negative on success */
return is_valid ? 1 : 0;
}

JoeyJ
- 188
- 2
- 11
-
I guess the link is dead. Any chance that the tutorial is still live anywhere else? – miho Dec 13 '14 at 13:07
-
Updated answer to have sample code. Anyone want to explain the downvotes or just due to deadlink? – JoeyJ Dec 15 '14 at 22:50
-
Thanks for the sample. Don't know, hasn't been me. – miho Dec 15 '14 at 22:56
0
It appears that it is not exactly easy to do in Objective C, but there are several ideas listed at this S.O. question: Possible to validate xml against xsd using Objc/iPhone code at runtime
It seems CodeSynthesis supports this here : http://wiki.codesynthesis.com/Using_XSDE_in_iPhone_Applications
I am really just pulling links and ideas from the Stack Overflow question at this point, though.
-
Yeah I did see the CodeSynthesis, though I wasn't crazy about it since its GPL and the setup for using in iOS seemed outdated and hard to follow =/ – JoeyJ Jun 22 '12 at 21:59
0
There is not a general schema validator. Try using XSDE as proposed above. It is very fast and very, very reliable.
Nice tutorial is here: http://amateuritsolutions.blogspot.hu/2012/10/validate-xsd-schema-in-your-ios.html

Teddy
- 1,056
- 1
- 14
- 24