tags:

views:

47

answers:

2

I just started switching my old DTD over to XSD when I found out about it, and I am wondering how I can enforce the XSD with my XML files? I have seen the W3C validator out there for it, but I wish that there was a way to make the program not run in the browser if an XSD error was found. Is that possible?

+3  A: 

Yes, this is possible using validating XML parsers, which are available for most general purpose languages.

OK, so it's PHP, then, directly from the first google hit on "validating XML PHP":

<?php

$xml = new DOMDocument(); 
$xml->load('./lures.xml');

if (!$xml->schemaValidate('./lures.xsd')) { 
   echo "invalid<p/>";
} 
else { 
   echo "validated<p/>"; 
} 

?>
unbeli
Any suggestions on that?
Metropolis
sure, as soon as you tell us what language/environment are you developing for
unbeli
I didnt really care so much about using a parser....I already knew that could be done. What I really was wondering is if it could be done directly from when the page loads in the browser. But thanks a lot for the example :) +1. I also did not really appreciate the "first google hit" as if I did not already look for it. I would not be here if I had not.
Metropolis
then you need to elaborate more. What XML are you validating? Is it part of the page content? Is it something else? Where does it come from?
unbeli
Well until I put the question up....I did not think it needed that much detail. Because I guess I was not looking for a way to do it inside a language....I was asking if it could be done from a browser.
Metropolis
@Metropolis - browsers contain and use XML parsers. Normally they don't do validation against XSDs.
Oded
@Oded +1 And that annoys me lol.....I wish they did. I kinda figure the whole point of adding a validation file to the XML file is that you want it to be validated. Do you think this will ever change in the future?
Metropolis
@Metropolis - probably not. It adds quite a lot of logic for something most people don't need...
Oded
@Oded Good to know. Thanks for the info.
Metropolis
+2  A: 

Enforcing of XSD rules cannot be done directly within XML, as it is a textual file format and has not intrinsic logic or way to check itself for validity.

In order to enforce the rules, you need to use a validating parser - this parser can load the XML and XSD and check the XML for validity against the XSD. This is also true for DTDs.

Oded
@Oded So if this is the case....Is there any reason to reference the .xsd file from the .xml file?
Metropolis
@Metropolis - It is handy as a reference, if nothing else. You could use a parser to extract the XSD reference in order to find/get the XSD and validate against it.
Oded