Link to home
Start Free TrialLog in
Avatar of pennypiper
pennypiper

asked on

Use libxml2 under linux to validate xpath against schema

Hello,

I have a question regarding programming libxml2 in C under linux.

Assume an XSD file called test.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="test" type="Test-Type"/>
    <xs:complexType name="Test-Type">
        <xs:all>
            <xs:element name="test-type-1"  type="xs:string"/>
            <xs:element name="test-type-2"  type="xs:integer"/>
        </xs:all>
    </xs:complexType>
</xs:schema>

And an XML file called test.xml:

<test>
  <test-type-1>foo</test-type-1>
  <test-type-2>1</test-type-2>
</test>


We can verify that this schema validates like this:
$ xmllint --noout --schema test.xsd test.xml
test.xml validates


It is trivial to write a program to validate an entire XML file against a schema.  For instance, if I can use this snippet:

  ctxt = xmlSchemaNewParserCtxt("test.xsd");
  schema=xmlSchemaParse(ctxt);

To verify the XSD file and then:
   
  doc = xmlReadMemory (xml_buf, strlen(xml_buf), NULL, NULL, 0);
  schemaErrors = xmlSchemaValidateDoc(ctxt, doc);
 
to validate the xml file against the XSD schema.  

So my question:  what if I want to validate not an ENTIRE xml document but only PART of one?  
I'd like to only check an xpath -- not an entire XML document -- for validation.  For instance, have a buffer containing:

"<test-type-2>10</test-type-2"

and validate that against the test.xsd file.  So if the buffer contained
"<test-type-2>foo</test-type-2>"

receive the libxml2 error message:

"Schemas validity error : Element 'test-type-2': 'foo' is not a valid value of the atomic type 'xs:integer'.
test.xml fails to validate"


I think the libxml2 function xmlSchemaValidateOneElement() is what I need to use, but I can't get it work.

Any thoughts or ideas?

Thanks!



Avatar of Infinity08
Infinity08
Flag of Belgium image

If I recall correctly, xmlSchemaValidateOneElement starts validating the subtree starting from the given node. However, that given node has to be a valid root node for the schema. In your case, it has to be a 'test' node.

I'm not aware of a way to do what you want in libxml2 though ...
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pennypiper
pennypiper

ASKER

Thanks Geert.