How to Validate Elements using XML Schema
Is there a way to use an XML Schema to validate if elements or attributes of a given path add up to be a certain total? The only schema element I've seen that uses XPath to view multiple elements or attribues of a scope is <xs:unique>. Seems so close, if only it could take an XSL math function to evaluate. But only a few validators I've seen online support <xs:unique>, so it's difficult to experiment.
Code:
<pie>
<slice percent="20">A</slice>
<slice percent="85">B</slice>
<slice percent="15">C</slice>
</pie>
Re: How to Validate Elements using XML Schema
It is necessary only to ensure that the XML document is associated with (at least) one. There are two ways to do that:
With a schema declaration in the XML document
By specifying the schema(s) to use in the application
To specify the schema definition in the document, you create XML like this:
Code:
<documentRoot
xmlns:xsi="http://www.site_name.com/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='YourSchemaDefinition.xsd'
>
The first attribute defines the XML namespace (xmlns) prefix, xsi, which stands for "XML Schema instance." The second line specifies the schema to use for elements in the document that do not have a namespace prefix--that is, for the elements you typically define in any simple, uncomplicated XML document. (You'll see how to deal with multiple namespaces in the next section.)
You can also specify the schema file in the application:
static final String schemaSource = "YourSchemaDefinition.xsd";
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
...
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance()
...
factory.setAttribute(JAXP_SCHEMA_SOURCE,
new File(schemaSource));
Note: When the application specifies the schema(s) to use, it overrides any schema declarations in the document.
Re: How to Validate Elements using XML Schema
You can use Schematron as a second layer of validation that will allow you to test arbitrary XPath assertions about your XML document. There's a fairly old article about embedding Schematron in XSD that you might find helpful.
Re: How to Validate Elements using XML Schema
You need use the -s option as well. This will turn on schema validation. When you don't supply the parser will attempt to validate against a DTD, hence the error messages you received.