This repository was archived by the owner on May 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDocValidator.cs
94 lines (82 loc) · 2.93 KB
/
DocValidator.cs
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.Schema;
namespace RCNet.XmlTools
{
/// <summary>
/// Implements the xml document loader and validator.
/// </summary>
public class DocValidator
{
//Constants
//Attributes
private readonly XmlSchemaSet _schemaSet;
//Constructor
/// <summary>
/// Creates an uninitialized instance.
/// </summary>
public DocValidator()
{
_schemaSet = new XmlSchemaSet();
return;
}
//Methods
/// <summary>
/// Adds the specified xml schema into the schema set.
/// </summary>
/// <param name="xmlSchema">The xml schema to be added.</param>
public void AddSchema(XmlSchema xmlSchema)
{
//Add the schema into the schema set
_schemaSet.Add(xmlSchema);
return;
}
/// <summary>
/// Loads the xml schema from a stream and adds it into the schema set.
/// </summary>
/// <param name="schemaStream">The stream to load from.</param>
public void AddSchema(Stream schemaStream)
{
//Load the schema
XmlSchema schema = XmlSchema.Read(schemaStream, new ValidationEventHandler(XmlValidationCallback));
//Add the schema into the schema set
AddSchema(schema);
return;
}
/// <summary>
/// Loads the xml document from file.
/// </summary>
/// <remarks>
/// The xml document is validated against the internal SchemaSet.
/// </remarks>
/// <param name="filename">The name of the xml file.</param>
public XDocument LoadXDocFromFile(string filename)
{
var binDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
XDocument xDoc = XDocument.Load(Path.Combine(binDir, filename));
xDoc.Validate(_schemaSet, new ValidationEventHandler(XmlValidationCallback), true);
return xDoc;
}
/// <summary>
/// Loads the xml document from string.
/// </summary>
/// <remarks>
/// The xml document is validated against the internal SchemaSet.
/// </remarks>
/// <param name="xmlContent">The xml content.</param>
public XDocument LoadXDocFromString(string xmlContent)
{
XDocument xDoc = XDocument.Parse(xmlContent);
xDoc.Validate(_schemaSet, new ValidationEventHandler(XmlValidationCallback), true);
return xDoc;
}
/// <summary>
/// The callback function called during the xml validation.
/// </summary>
private void XmlValidationCallback(object sender, ValidationEventArgs args)
{
throw new InvalidOperationException($"Validation error: {args.Message}");
}
}//DocValidator
}//Namespace