QuantDev said:
I would need to validate an XML fragment against a type defined within
an XSD (which defines many other things). What is the correct way of
achieving this?
That depends on the validating XML parser you are using, for instance
MSXML 5, Microsoft COM based XML parser version 5, currently only
available with other MS software like Office 2003, has a method named
validateNode
for its XML DOM document that allows you to validate the node (including
any descendants) against the currently loaded schemas.
Unfortunatly that functionality is not available in MSXML 4, the version
you can download from
http://msdn.microsoft.com/.
The documentation for the method of MSXML 5 is here:
<
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmmth_validateNode.asp>
If you have a simple schema constraining the contents of <god> elements
to NCNames:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="
http://www.w3.org/2001/XMLSchema"
version="1.0">
<xs:element name="gods">
<xs:complexType>
<xs:sequence>
<xs:element name="god" type="xs:NCName" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
and an instance like
<?xml version="1.0" encoding="UTF-8"?>
<gods
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="test2005040701Xsd.xml">
<god>Kibo</god>
</gods>
then the following client-side JScript example adds an new element with
content requested from the user and then validates the newly introduced
node:
var xmlDocument = new ActiveXObject('Msxml2.DOMDocument.5.0');
xmlDocument.async = false;
var valid = xmlDocument.load('test2005040701.xml');
if (valid) {
var newGod = xmlDocument.createElement('god');
var newName = prompt('Who is your GOD?', '');
newGod.appendChild(xmlDocument.createTextNode(newName));
xmlDocument.documentElement.appendChild(newGod);
var parseError = xmlDocument.validateNode(newGod);
if (parseError.errorCode != 0) {
alert(parseError.reason);
}
else {
alert(xmlDocument.xml);
}
}
The new validation API in Java 1.5 also allows you to validate a DOM
node against a loaded schema.