C#个人常用标准库 > XmlTool


Xml反序列话工具


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZmjTool
{
    public class XmlTool
    {
        /// <summary>
        /// 尝试将string序列化为class数组
        /// </summary>
        /// <param name="htmlstr"></param>
        /// <param name="eles"></param>
        /// <param name="message">输出序列化中遇到的错误提示</param>
        /// <returns></returns>
        public static bool Parse(string htmlstr, ref System.Security.SecurityElement eles, ref string message)
        {
            try
            {
                eles = System.Security.SecurityElement.FromString(htmlstr);
                message = string.Empty;
                return eles != null;
            }
            catch (Exception e)
            {
                eles = null;
                message = "sitemap文档解析异常:" + e.Message;
                return false;
            }
        }
        /// <summary>
        /// children中查找相关的tag
        /// </summary>
        /// <param name="e"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static System.Security.SecurityElement[] GetElements(System.Security.SecurityElement e, string tag)
        {
            var le = new List<System.Security.SecurityElement>();
            if (e.Children == null) return le.ToArray();
            foreach (System.Security.SecurityElement item in e.Children) if (item.Tag.ToLower().Equals(tag)) le.Add(item);
            return le.ToArray();
        }
        /// <summary>
        /// 尝试获取一个ele的属性中的encoding标记
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string[] GetAttribute(System.Security.SecurityElement es, string attname)
        {
            List<string> la = new List<string>();
            if (es.Attributes == null) return la.ToArray();
            foreach (System.Collections.DictionaryEntry item in es.Attributes) if (item.Key is string tag && tag.ToLower().Equals(attname)) la.Add(item.Value?.ToString() ?? string.Empty);
            return la.ToArray();s
        }
    }
}