2009-12-08 63 views
2

我在本地的xsd文件中有一些XML和XML Schema。 XML文檔不包含任何模式信息。我想根據Cocoa中的xsd模式文件來驗證XML文檔(這意味着我更喜歡基於NS/CF/libxml而不是外部庫)。使用Cocoa中的xsd文件驗證XML Schema?

我可以通過xmllint,這可能會工作,但我正在尋找一種方法來做到這一點,而無需啓動外部任務。

回答

3

如果你的XML文檔不有參考xml架構,你守ld自己添加它,然後使用NSXMLDocument validateAndReturnError:方法進行驗證。

下面是如何調整xml文檔以引用xsd的示例。顯然,你將不得不調整這段代碼來引用你的本地xsd文件。

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]); 
2

那麼,xmllint是libxml工具之一。 xmllint的XSD驗證部分只是libxml模式模塊的一個小包裝 - 您可以看到API here。我從Cocoa自己使用過。