XML Schema validation ignored when fragment-level conformance is enabled?
From my sojourn with XML and Schema validation, it seems that when fragment-level conformance is enabled for an XMLReader instance, the XML source st开发者_运维百科ops being validated against any included Schemas.
However I cannot verify this from the MSDN documentation as it doesn't seem to describe XSD Schema behaviour in light of conformance level. Also if I assume this problem is true, I cannot find a workaround for it.
I would like to know how to validate a XML fragment against an XSD Schema.
In my case I'm validating against the XHTML 1 Strict Schema. By the fact deprecated HTML tags like <center> are not being flagged as invalid, this is part of the reason I believe fragment conformance ignores schema. Also when I use document-level conformance in the same scenario, validity errors are successfully flagged.
For a code sample of the type of validation scenario I'm using see this.
I think I found the answer in this MSKB article oddly enough titled HOW TO: Validate XML Fragments Against an XML Schema in Visual C#.NET The bottom of the article states:
NOTE: Only the type declarations and the top-level elements in the XML schema are validated against an XML schema. Subelements are considered as local and therefore cannot be validated. In order to validate a subelement, declare a top-level element and refer to that.
I believe there is a mistake in that paragraph and the intention is to state top-level elements in the XML
schema
document/fragment
are validated against an XML Schema
Because the Microsoft code sample starts its fragment at the top level (instead of arbitrarily inside a document) it works with validation. However in my case I'm taking a mid-document construct.
Correct me if my interpretation is wrong.
Workaround/solution
A workaround is for me to stuff my fragments inside a top level element for the purpose of validation.
In other words if I'm dealing with the XHTML fragment:
<div>MY FRAGMENT</div>
I can wrap it for validation to conform to the XHTML Strict Schema as:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML fragment enclosed, conforming to XHTML 1.0 Strict Template.</title>
</head>
<body>
<div>MY FRAGMENT</div>
</body>
</html>
This solution works for me so I'll use it in the interim; whether or not a better solution exists I'm unsure yet.
精彩评论