I use the following code to validate a xml file against a xsd file.
var result = false;
var xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
result = true;
}
catch (XmlSchemaValidationException ex)
{
result = false;
_logger.Error($"{ex.Message}");
}
It works but I only get the error message, I would like to retrieve the actual value in the xml file that fail. For example, in the xsd file I have this
<xs:element name="Car" maxOccurs="1" minOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="Volvo|Tesla|Skoda"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
And the XML file contains the value Ford in the Car element. How can I retrieve the "Ford" value that is failing against the validation?
I found a way, I can add this inside the catch(XmlSchemaValidatorException ex)..
var node = ex.SourceObject as XmlNode;
Then I'm able to get the node.InnerText which contains the faulty value