Search code examples
c#xml.net-2.0xsdxml-validation

Validating xml nodes, not the entire document


I'm working with some xml 'snippets' that form elements down the xml. I have the schema but I cannot validate these files because they are not complete xml documents. These snippets are wrapped with the necessary parent elements to form valid xml when they are used in other tools so I don't have much option in making them into valid xml or in changing the schema.

Is it possible to validate an element, rather than the whole document? If not, what workarounds could be suggested?

I'm working in C# with .NET 2.0 framework.


Solution

  • I had a similar problem where I could only validate parts of my XML document. I came up with this method here:

    private void ValidateSubnode(XmlNode node, XmlSchema schema)
    {
        XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);
    
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        settings.Schemas.Add(schema);
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler);
    
        using (XmlReader validationReader = XmlReader.Create(reader, settings))
        {     
            while (validationReader.Read())
            {
            }
        }
    }
    
    private void XSDValidationEventHandler(object sender, ValidationEventArgs args)
    {
        errors.AppendFormat("XSD - Severity {0} - {1}", 
                            args.Severity.ToString(), args.Message);
    }
    

    Basically, I pass it an XmlNode (which I select from the entire XmlDocument by means of .SelectSingleNode), and an XML schema which I load from an embedded resource XSD inside my app. Any validation errors that might occur are being stuffed into a "errors" string builder, which I then read out at the end, to see if there were any errors recorded, or not.

    Works for me - your mileage may vary :-)