QuantDev wrote:
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_validateN ode.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="unbo unded" />
</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:noNamespace SchemaLocation= "test2005040701 Xsd.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.DOMDocum ent.5.0');
xmlDocument.asy nc = false;
var valid = xmlDocument.loa d('test20050407 01.xml');
if (valid) {
var newGod = xmlDocument.cre ateElement('god ');
var newName = prompt('Who is your GOD?', '');
newGod.appendCh ild(xmlDocument .createTextNode (newName));
xmlDocument.doc umentElement.ap pendChild(newGo d);
var parseError = xmlDocument.val idateNode(newGo d);
if (parseError.err orCode != 0) {
alert(parseErro r.reason);
}
else {
alert(xmlDocume nt.xml);
}
}
The new validation API in Java 1.5 also allows you to validate a DOM
node against a loaded schema.
--
Martin Honnen
http://JavaScript.FAQTs.com/