/// <summary> /// XElement动态解析 /// </summary> public class XElmentObject : DynamicObject { private XElement _root; #region ///this[string name] 属性索引器 /// <summary> /// 属性索引器 /// </summary> /// <param name="name">属性的Name</param> /// <returns>属性的值</returns> public string this[string name] { get { if (_root == null) { return String.Empty; } var attr = _root.Attribute(name); if (attr != null) { return attr.Value; } else { return String.Empty; } } } #endregion #region ///Load 加载xml文件 public void Load(string str) { _root = XElement.Load(str); } #endregion #region ///Parse 序列化xml字符串 public void Parse(string str) { _root = XElement.Parse(str); } #endregion #region ///Parse 序列化xml字符串 public void Parse(XElement xe) { _root = xe; } #endregion #region ///ToString public override string ToString() { if(_root==null) { return String.Empty; } return _root.ToString(); } #endregion #region ///TryGetMember /// <summary> /// 当获取非静态声明代码调用 /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder,out object result) { result = String.Empty; //还没有匹配xml,返回空字符串 if (_root == null) { result = String.Empty; } //获取子列表 var xList = _root.Elements(binder.Name); //异常 if (xList == null) { return true; } //子列表不为空 if (xList.Any()) { var list = new List<XElmentObject>(); foreach (var item in xList) { XElmentObject obj = new XElmentObject(); obj.Parse(item); list.Add(obj); } result = list; } else { result = this[binder.Name]; } return true; } #endregion }
xml文件
<?xml version="1.0" encoding="utf-8"?> <Root> <persons> <Person Name="张三" /> <Person Name="李四" /> </persons> </Root>测试
class Program { static void Main(string[] args) { string path = @"Persons.xml"; XElmentObject xml = new XElmentObject(); xml.Load(path); dynamic root = xml; Console.WriteLine(root.Persons[0].Person[0].Name); } }
结果
张三 请按任意键继续. . .