天天看點

C#讀寫xml總結

private void readXml() 
        {
            // 讀取的基本思路:
            // 可以一次擷取一個節點清單出來:XmlNodeList = XmlDocument.GetElementsByTagName("節點名稱")
            // 周遊這個節點清單:foreach (XmlElement item in xmlNodeList) {}
            // 擷取一個節點的屬性值:XmlElement.GetAttribute("屬性名");
            // 擷取一個節點的子節點清單:XmlNodeList = XmlElement.ChildNodes;
            // 擷取XmlNodeList的某個子節點:xnl[i]
            // 擷取XmlNodeList的某個子節點的節點值:xnl[i].InnerXml

            string fileName = @"D:\test.xml";
            XmlDocument xd = new XmlDocument();
            xd.Load(fileName);
            XmlNodeList xmlNodeList = xd.GetElementsByTagName("user");
            List<User> users = new List<User>();

            foreach (XmlElement item in xmlNodeList) 
            {
                User user = new User();
                user.Id = int.Parse(item.GetAttribute("id"));
                XmlNodeList xnl = item.ChildNodes;
                user.Name = xnl[0].InnerXml;
                user.Age = int.Parse(xnl[1].InnerXml);
                user.Gender = xnl[2].InnerXml;
                users.Add(user);
            }
            foreach (var item in users) 
            {
                Debug.WriteLine(item);
            }
        }

        private void writeXml()
        {
            // 基本思路是:
            // 建立xml聲明:XmlNode = XmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            // 建立一個節點:XmlElement = XmlDocument.CreateElement("節點名");
            // 給節點設定屬性:XmlElement.SetAttribute("屬性名","屬性值");
            // 給節點設定Text:XmlElement.InnerText = "值"
            // 添加子節點到父節點:XmlElement.AppendChild(子節點);


            Debug.WriteLine("test ok!");

            string fileName = @"D:\test.xml";
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode header = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmlDoc.AppendChild(header);

            XmlElement rootNode = xmlDoc.CreateElement("users");

            List<User> list = GetUsers();
            foreach (var item in list) 
            {
                XmlElement xn = InsertUser(item, xmlDoc);
                rootNode.AppendChild(xn);
            }
            xmlDoc.AppendChild(rootNode);
            xmlDoc.Save(fileName);
        }

        private static XmlElement InsertUser(User user, XmlDocument xmlDoc) 
        {
            // 建立一個節點,标簽是user
            XmlElement xn = xmlDoc.CreateElement("user");
            // 給這個節點設定一個屬性名為id,并為此屬性指派
            xn.SetAttribute("id", user.Id + "");
            // 此标簽下append新的節點
            xn.AppendChild(GetXmlNode(xmlDoc,"name",user.Name));
            xn.AppendChild(GetXmlNode(xmlDoc, "age", user.Age + ""));
            xn.AppendChild(GetXmlNode(xmlDoc, "gender", user.Gender));
            return xn;
        }

        private static XmlElement GetXmlNode(XmlDocument xmlDoc, string name, string value) 
        {
            // 建立一個節點,被賦予text值,但是不賦予屬性
            XmlElement xn = xmlDoc.CreateElement(name);
            xn.InnerText = value;
            return xn;
        }

        private static List<User> GetUsers() 
        {
            List<User> list = new List<User>();
            for (int i = 0; i < 10; i++) 
            {
                User user = new User();
                user.Id = i;
                user.Name = "Name" + i;
                user.Age = 15;
                user.Gender = "男";
                list.Add(user);
            }
            return list;
        }
           

user類:

class User
    {
        public int Id { set; get; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { set; get; }
        public override string ToString()
        {
            return Id + "," + Name + "," + Age + "," + Gender;
        }
    }
           

// 注意非法字元轉義

&lt;  <  小于

&gt; >  大于

&amp;  &  和号

&apos;  '  單引号

&quot;   "  雙引号

隻需要在xml裡面,對應的非法字元替換為左邊的轉義字元,則讀寫都按照當沒有這個轉義存在一樣

比如xml裡:

<add key="key1" value="hello"/>
      <add key="key2" value="world!"/>
      <add key="CIF" value="1"/>
      <add key="C&amp;F" value="2"/>
      <add key="FOB" value="3"/>
      <add key="C&amp;I" value="4"/>
      <add key="市場價" value="5"/>
      <add key="墊倉" value="6"/>
           

在代碼裡如常通路:

string key1 = ConfigSettings.ReadSetting("C&F");
            Debug.WriteLine("C&F=" + key1);
           

其他:

讀取路徑下所有xml檔案:

var files = Directory.GetFiles(readPath, "*.xml");
            foreach (var file in files) 
            {
                Debug.WriteLine("file=" + file);
            }
           
file=D:\download\CTRCV2017020810421600037160562.xml
file=D:\download\CTRCV2017022315481300041130625.xml
           

或者:

DirectoryInfo folder = new DirectoryInfo(readPath);

            foreach (FileInfo file in folder.GetFiles("*.xml"))
            {
                Debug.WriteLine(file.FullName);
            }
           
D:\download\CTRCV2017020810421600037160562.xml
D:\download\CTRCV2017022315481300041130625.xml
           

如果路徑不存在則建立:

if (Directory.Exists(readPath + @"\BACKUP") == false) 
                    {
                        Directory.CreateDirectory(readPath + @"\BACKUP");
                    }
           

把檔案拷貝到另一個目錄:

System.IO.File.Copy(path, readPath + @"\BACKUP\" + fileName);
           

删除某個檔案:

File.Delete(path);
           

參考這裡:https://www.cnblogs.com/hhzz/p/6592452.html