iphone - iOS 上的 XSD 验证

标签 iphone ios xml xsd xsd-validation

我想根据 iOS 上的 XSD 验证 XML 文件。文档暗示使用 NSXMLDocument 来执行此操作,但它在 iOS 上不可用 =(。在 iOS 上是否有任何轻量级替代方案来执行此操作?

最佳答案

我最终使用了 libxml2 中的验证工具,因为它是一个已经包含在 iOS 中的库。按照这个示例代码

#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;
}

关于iphone - iOS 上的 XSD 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11163514/

相关文章:

xml - 如何允许 xml :lang attribute in XMLSchema?

iphone - 将 iPhone 3-D 游戏代码转换为在 Android 设备上运行的最佳方式?

ios - 后置和前置摄像头一起打开

ios - iOS SDK 支持字符串中使用的符号的意义

ios - 在不减慢 UI 的情况下在 UITableViewCell 中显示 MKMapView

javascript - 是否存在与 JavaScript 方法 encode() 等效的 Objective C?

java - 调整序列化 DOM 中的 XML 命名空间声明样式

ios - 如何在 ios swift 中将相机预览 View 添加到三个自定义 uiview

ios - 如何使用 iPhone SDK 创建动态 UITableView 单元格

ios - 当 View 在 ScrollView 内时 onTapGesture 不工作?