Menu

#1 How to use the .XSD file for XML validation

open
nobody
None
5
2006-03-10
2006-03-10
Satish
No

hi,

I have tried to run the simpleserver and client and
they are running successfully.
Can I add a .xsd file (XML schema file) at either or
both end to validate the message that has
sent/received ?

Please let me know it is possible or not. If possible
then guide me the steps that I have to follow for this.

Regards,
Satish

Discussion

  • Nobody/Anonymous

    Logged In: NO

    Here's an example, it's striped down to the bones!
    - no *free*
    - no error checking
    - no further restriction in the schema
    - ...

    1. I created a simple service, which response with the value of time() :
    soap_env_add_itemf(res->env, NULL, "seconds", "%d", time(NULL));

    2. My "gettime.xsd" :
    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema
    elementFormDefault="qualified"
    xmlns="urn:examples"
    targetNamespace="urn:examples"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="getTimeResponse">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="seconds" type="xsd:int"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>

    3. A function for the validation :
    int
    is_valid_method(char *xsd_file, xmlNodePtr method)
    {
    xmlDocPtr xsd_doc, doc;
    xmlNodePtr root;
    xmlSchemaParserCtxtPtr xsd_ctxt;
    xmlSchemaPtr xsd;
    xmlSchemaValidCtxtPtr valid_ctxt;

    /* process the schema */
    xsd_doc = xmlReadFile(xsd_file, NULL, 0);
    xsd_ctxt = xmlSchemaNewDocParserCtxt(xsd_doc);
    xsd = xmlSchemaParse(xsd_ctxt);

    /* create a new doc from the "method" element for easier handling */
    valid_ctxt = xmlSchemaNewValidCtxt(xsd);
    doc = xmlNewDoc(BAD_CAST "1.0");
    root = xmlCopyNode(method, 1);
    xmlDocSetRootElement(doc, root);

    if (xmlSchemaValidateDoc(valid_ctxt, doc)) {
    return 0; /* not valid */
    } else {
    return 1; /* valid */
    }
    }

    4. validate the response in the client :
    ...
    if (!is_valid_method("gettime.xsd", soap_env_get_method(response->env))) {
    fprintf("kick this service!\n");
    return 1;
    }
    ...

    That's all. To verify the validation you may replace the service response with :
    soap_env_add_item(res->env, NULL, "seconds", "humppa");

     
  • Nobody/Anonymous

    Logged In: NO

    Ups, printf, not fprintf

    greetings, Daniel

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.