C# 讀寫xml

浪花一朵朵發表於2013-07-05

.net3.5及以上框架增強了對xml的支援,操作xml非常方便,下面分別用.net2.0及.net3.5及以上版本操作xml。

.net2.0版本讀xml的demo:特別適用於配置檔案的讀取,類似於下面的這種情況:

<?xml version="1.0" encoding="utf-8"?>
<SAP>
  <aa>編碼</aa>
<bb>名稱</bb> 
</SAP>

程式碼:

        /// <summary>
        /// 讀取xml返回字典
        /// </summary>
        /// <param name="xmlPath">絕對路徑</param>
        /// <param name="nodeName">節點名</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetAllData(string xmlPath, string nodeName)
        {
            XmlDataDocument xmlDoc = new XmlDataDocument();
            xmlDoc.Load(xmlPath);
            XmlNode xn = xmlDoc.SelectSingleNode(nodeName);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            try
            {
                foreach (XmlNode xnf in xn)
                {
                    XmlElement xe = xnf as XmlElement;
                    dic.Add(xe.Name, xe.InnerText);
                }
            }
            catch (Exception)
            {
                return null;
            }
            return dic.Count > 0 ? dic : null;
        }

用linq讀xml:

        public ObservableCollection<Tree> GetTreeList()
        {
            try
            {
                XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
                XDocument xDocument = XDocument.Load(xmlReader);
                var quota = from p in xDocument.Descendants("ID").Descendants("PID").Descendants("Pic").Descendants("Name")
                            select new Tree
                            {
                                Name = p.Attribute("Name").Value,
                                ID = p.Attribute("ID").Value,
                                Pic = p.Attribute("Pic").Value,
                                PID = p.Attribute("PID").Value
                            };
                if (quota != null)
                {
                    foreach (var item in quota)
                    {
                        Tree tree = new Tree { ID = item.ID, Name = item.Name, PID = item.PID, Pic = item.Pic };
                        treeList.Add(tree);
                    }
                }
                return treeList;
            }
            catch (Exception)
            {
                throw;
            }
        }

對應xml為:

<?xml version="1.0" encoding="utf-8" ?>
<Tree>
  <TreeNode ID="01" Name="sddd" PID="0" Pic="" ></TreeNode>
  <TreeNode ID="02" Name="ddd" PID="0" Pic="" ></TreeNode>
  <TreeNode ID="03" Name="dddd" PID="0" Pic="" ></TreeNode>
  <TreeNode ID="0121" Name="qqq" PID="01" Pic="" FontSize="12"></TreeNode>
  <TreeNode ID="0122" Name="tttt" PID="01" Pic="" FontSize="12"></TreeNode>
  <TreeNode ID="0123" Name="ttss" PID="01" Pic="" FontSize="12"></TreeNode>

</Tree>

通過對比,顯然高版本的.net framework操作xml簡單方便得多,而且可讀性強。

 

 

 

相關文章