views:

430

answers:

3

I have some XML and an XML Schema in a local xsd file. The XML document does not contain any schema information. I want to validate the XML document against the xsd schema file in Cocoa (meaning I'd prefer something NS/CF/libxml based as opposed to an external library).

I can across xmllint, which would probably work, but I was looking for a way to do it without launching an external task.

+2  A: 

Well, xmllint is one of the libxml tools. The XSD validation part of xmllint is simply a small wrapper around the schema module of libxml - you can see the API here. I've used this from Cocoa myself.

Nic Gibson
A: 

Newt is correct. I have some open source Cocoa code that uses the libxml XSD API.

The project is here:

http://code.google.com/p/cocoatron/

Specifically this method:

- (void)doXSDValidation:(xmlDocPtr)source;

In this file:

http://code.google.com/p/cocoatron/source/browse/trunk/ValidateXMLDocuments/Validate%20XML%20Documents.m

Todd Ditchendorf
+1  A: 

If your xml document does not have a reference to the xml schema, you should add it yourself, then validate with NSXMLDocument validateAndReturnError: method.

Here is an example of how to tweak the xml document to have a reference to the xsd. Obviously, you will have to adapt this code to have a reference to your local xsd file.

NSError *error = nil;
NSURL *xmlURL = [NSURL URLWithString:@"http://www.xmlschema.info/PO.xml"];

NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:xmlURL options:NSXMLNodeOptionsNone error:NULL];

NSXMLNode *noNamespaceSchemaLocation = [NSXMLNode attributeWithName:@"xsi:noNamespaceSchemaLocation" stringValue:@"http://www.xmlschema.info/PO.xsd"];
NSXMLElement *rootElement = [document rootElement]; 
NSMutableArray *rootAttributes = [[rootElement attributes] mutableCopy];
[rootAttributes replaceObjectAtIndex:1 withObject:noNamespaceSchemaLocation];
[rootElement setAttributes:rootAttributes];

BOOL isValid = [document validateAndReturnError:&error];

if (isValid)
    NSLog(@"document is valid");
else
    NSLog(@"document is invalid: %@", [error localizedDescription]);
0xced