This repository has been archived by the owner on Oct 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommentXmlConfigReader.cs
68 lines (62 loc) · 2.06 KB
/
CommentXmlConfigReader.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace SilverConfig
{
public class CommentXmlConfigReader<T> : IConfigReader<T>
{
private readonly XmlSerializer serializer;
public CommentXmlConfigReader()
{
serializer = new XmlSerializer(typeof(T));
}
public virtual T? Read(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException();
}
using var streamWriter = new StreamReader(path);
using var xmlReader = XmlReader.Create(streamWriter);
return (T?)serializer.Deserialize(xmlReader);
}
public virtual bool SupportsComments()
{
return true;
}
public virtual void Write(T config, string path)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
using var streamWriter = new StreamWriter(path, false);
MakeDocumentWithComments(XmlUtils.SerializeToXmlDocument(config)).Save(streamWriter);
}
private static XmlDocument MakeDocumentWithComments(XmlDocument xmlDocument)
{
foreach (var i in typeof(T).GetMembers())
{
foreach (var e in i.GetCustomAttributes(false))
{
if (e is CommentAttribute a)
{
if (a.InsideOfObject)
{
xmlDocument = XmlUtils.CommentInObject(xmlDocument, $"/{typeof(T).Name}/{i.Name}", a.Description);
}
else
{
xmlDocument = XmlUtils.CommentBeforeObject(xmlDocument, $"/{typeof(T).Name}/{i.Name}", a.Description);
}
}
}
}
return xmlDocument;
}
}
}