You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

163 lines
4.5 KiB
C#

3 years ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Newtonsoft.Json;
namespace Common
{
/// <summary>
/// xmldata 实体
/// </summary>
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; }
}
/// <summary>
/// Xml工具类
/// </summary>
public class XmlHelper
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="xmlPath"></param>
public XmlHelper(string xmlPath)
{
//初始化
Document = new XmlDocument();
//读取xml
Document.Load(xmlPath);
string json = JsonConvert.SerializeXmlNode(Document);
}
public XmlDocument Document { get; set; }
/// <summary>
/// 解析 LastUpdateDate2021-07-07 16:28:47.694 AuthorLingbug
/// </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);
//返回
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>();
}
}
}
}