using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using Newtonsoft.Json; namespace Common { /// /// xmldata 实体 /// public class XmlData { public string NodeName { get; set; } public Dictionary Attributes { get; set; } public string Text { get; set; } public List Children { get; set; } } /// /// Xml工具类 /// public class XmlHelper { /// /// 构造函数 /// /// public XmlHelper(string xmlPath) { //初始化 Document = new XmlDocument(); //读取xml Document.Load(xmlPath); string json = JsonConvert.SerializeXmlNode(Document); } public XmlDocument Document { get; set; } /// /// 解析 LastUpdateDate:2021-07-07 16:28:47.694 Author:Lingbug /// /// public (List TreeList, List DataList) Analysis() { //初始化 var list = new List(); var allList = new List(); //获取根结点 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 list, ref List 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(), }; if (child.Name == "#text") { //文本 item.Text = child.Value; } //返回 return item; } private Dictionary AnalysisElementAttribute(XmlNode element) { //属性 var attrList = element.Attributes; if (attrList != null && attrList.Count > 0) { //初始化 var dicAttr = new Dictionary(); for (int i = 0; i < attrList.Count; i++) { //属性 var attrItem = attrList[i]; //添加到字典 dicAttr.Add(attrItem.Name, attrItem.Value); } //返回 return dicAttr; } else { //返回 return new Dictionary(); } } } }