using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
namespace DBCHM.Common
{
///
/// 解析VS生成的 XML文档文件
///
public class XmlAnalyze
{
public Dictionary, List>> Data { get; set; } = new Dictionary, List>>();
public List EntityNames { get; set; } = new List();
public Dictionary EntityComments { get; set; } = new Dictionary();
private Dictionary EntityXPaths { get; set; } = new Dictionary();
public XmlAnalyze(string path)
{
var content = File.ReadAllText(path, Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
var rootNode = doc.DocumentElement;
var nodeList = rootNode.SelectNodes("//members/member[starts-with(@name,'T:')]");
foreach (XmlNode node in nodeList)
{
var value = node.Attributes["name"]?.Value;
var entityName = value?.Split('.')?.LastOrDefault();
//实体名 必须由 字母数字或下划线组成
if (Regex.IsMatch(entityName, @"^[a-z\d_]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase))
{
var comment = node?.InnerText?.Trim();
EntityNames.Add(entityName);
EntityComments.Add(entityName, comment);
var xpath = value?.Replace("T:", "P:") + ".";
EntityXPaths.Add(entityName, xpath);
}
}
foreach (var item in EntityXPaths)
{
var nodes = rootNode.SelectNodes($"//members/member[starts-with(@name,'{item.Value}')]");
var ecKey = new KeyValuePair(item.Key, EntityComments[item.Key]);
var lstKV = new List>();
foreach (XmlNode node in nodes)
{
var value = node.Attributes["name"]?.Value;
var propName = value?.Split('.')?.LastOrDefault();
var comment = node.InnerText?.Trim();
lstKV.Add(new KeyValuePair(propName, comment));
}
Data.Add(ecKey, lstKV);
}
}
}
}