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
2010-09-21 21:02:44
Any suggestions on that?
Metropolis
2010-09-21 21:03:33
sure, as soon as you tell us what language/environment are you developing for
unbeli
2010-09-21 21:04:25
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
2010-09-21 21:11:53
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
2010-09-21 21:13:23
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
2010-09-21 21:15:15
@Metropolis - browsers contain and use XML parsers. Normally they don't do validation against XSDs.
Oded
2010-09-21 21:18:42
@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
2010-09-21 21:21:02
@Metropolis - probably not. It adds quite a lot of logic for something most people don't need...
Oded
2010-09-21 21:25:02
@Oded Good to know. Thanks for the info.
Metropolis
2010-09-21 21:28:31
+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
2010-09-21 21:08:25
@Oded So if this is the case....Is there any reason to reference the .xsd file from the .xml file?
Metropolis
2010-09-21 21:59:48
@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
2010-09-22 08:00:53