.Net/.Net Core/.Net5中解析xml/xsd文件
定义实体XmlData
public class XmlData
{
public string NodeName { get; set; }
public Dictionary<string, string> Attributes { get; set; }
public string Text { get; set; }
public List<XmlData> Children { get; set; }
}
Xml工具类XmlHelper
/// <summary>
/// Xml工具类 LastUpdateDate:2021-07-07 16:08:53.390 Author:Lingbug
/// </summary>
public class XmlHelper
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="xmlPath"></param>
public XmlHelper(string xmlPath)
{
//初始化
Document = new XmlDocument();
//读取xml
Document.Load(xmlPath);
}
public XmlDocument Document { get; set; }
/// <summary>
/// 解析 LastUpdateDate:2021-07-07 16:28:47.694 Author:Lingbug
/// </summary>
/// <returns></returns>
public (List<XmlData> TreeList, List<XmlData> DataList) Analysis()
{
//初始化
var list = new List<XmlData>();
var allList = new List<XmlData>();
//获取根结点
XmlElement rootElement = Document.DocumentElement;
//根节点
var rootModel = CreateModelByNode(rootElement);
//添加到集合
list.Add(rootModel);
//添加到集合
allList.Add(rootModel);
//解析
AnalysisRecursion(rootElement, null, rootModel, ref list, ref allList);
//记录日志
LogHelper.Info("AnalysisXml - result【tree】:" + JsonConvert.SerializeObject(list));
//记录日志
LogHelper.Info("AnalysisXml - result【all】:" + JsonConvert.SerializeObject(allList));
//返回
return (list, allList);
}
private void AnalysisRecursion(XmlElement element, XmlNode node, XmlData parent, ref List<XmlData> list, ref List<XmlData> allList)
{
//子节点
XmlNode child = element == null ? node.FirstChild : element.FirstChild;
while (true)
{
//对象
var item = CreateModelByNode(child);
if (item == null)
{
//中止
break;
}
//添加到集合
allList.Add(item);
if (parent == null)
{
//添加到集合
list.Add(item);
}
else
{
if (!string.IsNullOrWhiteSpace(item.Text))
{
//赋值
parent.Text = item.Text;
}
else
{
//添加到集合
parent.Children.Add(item);
}
}
//递归
AnalysisRecursion(null, child, item, ref list, ref allList);
//下一个同级
child = child.NextSibling;
}
}
private XmlData CreateModelByNode(XmlNode child)
{
if (child == null)
{
//为空,不操作
return null;
}
//初始化
var item = new XmlData()
{
NodeName = child.Name,
Attributes = AnalysisElementAttribute(child),
Children = new List<XmlData>(),
};
if (child.Name == "#text")
{
//文本
item.Text = child.Value;
}
//返回
return item;
}
private Dictionary<string, string> AnalysisElementAttribute(XmlNode element)
{
//属性
var attrList = element.Attributes;
if (attrList != null && attrList.Count > 0)
{
//初始化
var dicAttr = new Dictionary<string, string>();
for (int i = 0; i < attrList.Count; i++)
{
//属性
var attrItem = attrList[i];
//添加到字典
dicAttr.Add(attrItem.Name, attrItem.Value);
}
//返回
return dicAttr;
}
else
{
//返回
return new Dictionary<string, string>();
}
}
}