I\'m running into real difficulties validating XML with XSD. I should prefix all of this and state up front, I\'m new to XSD and validation, so I\'m not sure if it\'s a code
I don't want the user to submit XML that's not defined in the XSD.
Why do you care? Your schema validates the XML nodes that are in your namespace. Your processing logic processes the XML nodes that are in your namespace. Nodes that aren't in your namespace aren't relevant to either your schema or your logic.
If it's truly essential to restrict all nodes in the XML document to a specific namespace, you can accomplish that by extending the basic XmlReader
validating logic found here.
public static void Main()
{
const string myNamespaceURN = "urn:my-namespace";
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(myNamespaceURN, "mySchema.xsd");
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += ValidationCallBack;
XmlReader reader = XmlReader.Create("myDocument.xml", settings);
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element ||
reader.NodeType == XmlNodeType.Attribute)
&&
reader.NamespaceURI != myNamespaceURN)
{
LogError(reader.NamespaceURI + " is not a valid namespace.");
}
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
LogError(e.Message);
}
private static void LogError(string msg)
{
Console.WriteLine(msg);
}