Capture Schema Information when validating XDocument

前端 未结 1 535
悲&欢浪女
悲&欢浪女 2020-12-06 07:46

This is similar to this question C# Get schema information when validating xml

However, I am working with an XDocument for LINQ purposes.

I am reading/parsin

相关标签:
1条回答
  • 2020-12-06 08:11

    For anyone who reads this question in the future, I managed to solve my problem, albeit in a slightly different way than i originally proposed.

    The first problem I was having, that the SchemaInfo both in the ValidationEventArgs and the GetSchemaInfo extension method of XElement were null. I resolved that in the same manner as in the question i linked originally....

    List<XElement> errorElements = new List<XElement>();
    
    serializedObject.Validate((sender, args) =>
    {
        var exception = (args.Exception as XmlSchemaValidationException);
    
        if (exception != null)
        {
            var element = (exception.SourceObject as XElement);
    
            if (element != null)
                errorElements.Add(element);
         }
    
    });
    
    foreach (var element in errorElements)
    {
        var si = element.GetSchemaInfo(); 
    
        // do something with SchemaInfo
    }
    

    It would appear that the Schema info is not added to the XObject until AFTER the validation callback, so if you try to access it in the middle of the validation callback, it will be null, but if you capture the element, then access if after the Validate method has completed, it will not be null.

    However, this opened up another problem. The SchemaInfo object model is not well documented and I had trouble parsing it out to find what I needed.

    I found this question after I asked my original question. The accepted answer links to a really great blog post that breaks down the SchemaInfo object model. It took me a bit of work to refine the code to suit my purposes, but it does a good job of illustrating how to get the SchemaInfo for any XmlReader element (which I was able to change to work with an XObject).

    0 讨论(0)
提交回复
热议问题