C Sharp - Validating XML data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Xml;
using System.Xml.Schema;

class XmlXsdValidator
{
public static void ValidateXmlAgainstXsd(string xmlFilePath, string[] xsdFilePaths, string[] targetNamespaces)
{
try
{
Console.WriteLine();
Console.WriteLine($"-- validate against {string.Join(", ", xsdFilePaths)} --");
Console.WriteLine();

// Create XML schema set
XmlSchemaSet schemas = new XmlSchemaSet();
for (int i = 0; i < xsdFilePaths.Length; i++)
{
schemas.Add(targetNamespaces[i], xsdFilePaths[i]);
}

// Create XML document
XmlDocument document = new XmlDocument();
document.Schemas = schemas;

// Load XML file
document.Load(xmlFilePath);

// Validation event handler
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallback);

// Validate XML document
document.Validate(eventHandler);

Console.WriteLine("XML validation completed successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error during XML validation: {ex.Message}");
}
}



// Callback method to handle validation errors
private static void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
Console.WriteLine($"Validation Error: {args.Message}");
}
else if (args.Severity == XmlSeverityType.Warning)
{
Console.WriteLine($"Validation Warning: {args.Message}");
}
}

// Main method for demonstration
public static void Main(string[] args)
{
string xmlFilePath = @"C:\d\dev\calpers457\TylerToCalPers457\Data\20241224093518_260_10006.xml";
string[] xsdFilePaths = {
@"C:\d\dev\calpers457\TylerToCalPers457\Data\SoapEnvelope.xsd",
@"C:\d\dev\calpers457\TylerToCalPers457\Data\CommonUtilitiesV1.xsd",
@"C:\d\dev\calpers457\TylerToCalPers457\Data\PayrollRetirementV1.xsd",
@"c:\d\dev\calpers457\TylerToCalPers457\Data\RetirementHealthTransactionsV1.xsd"
};
string[] targetNamespaces = {
http://schemas.xmlsoap.org/soap/envelope/,
http://calpers.ca.gov/PSR/CommonUtilitiesV1,
http://calpers.ca.gov/PSR/PayrollRetirementV1,
http://calpers.ca.gov/PSR/RetirementHealthTransactionsV1
};

ValidateXmlAgainstXsd(xmlFilePath, xsdFilePaths, targetNamespaces);

}
}

Notice the references to the xsd files. The last one isn’t even in the document. But it is part of payroll retirement v1.