C#操作xml文档增删改查(Linq to XML)

2021-05-29 22:17

阅读:606

标签:删除   each   sys   通过   catch   string   dom   结合   var   

1.创建xml

 1         public static void CreateXmlDoc()
 2         {
 3             XElement myDoc =
 4                 new XElement("Customers",
 5                     new XElement("Customer", new XAttribute("ID", "1"),
 6                         new XElement("Usename", "Rock  Zed"),
 7                         new XElement("FirstName", "Rock"),
 8                         new XElement("LastName", "Zed"),
 9                         new XElement("PhoneNo", "35481254")
10                     )
11                );
12             myDoc.Save("Customer.xml");
13         }

  创建的xml文档内容如下:

xml version="1.0" encoding="utf-8"?>
Customers>
  Customer ID="1">
    Usename>Rock  ZedUsename>
    FirstName>RockFirstName>
    LastName>ZedLastName>
    PhoneNo>35481254PhoneNo>
  Customer>
Customers>

2.获取XML文档内容

 1         #region Load XML doc
 2         public static XDocument GetXmlDoc()
 3         {
 4             try
 5             {
 6                 XDocument myDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
 7                 return myDoc;
 8             }
 9             catch (System.IO.FileNotFoundException ex)
10             {
11                 return null;
12             }
13         }
14         #endregion
15         //将xml内容与自定义类相对应 获取到对应类的集合
16         public static List GetXmlData()
17         {
18             List listCs = new List();
19             XDocument myDoc = XmlHelper.GetXmlDoc();
20             if (myDoc != null)
21             {
22                 var query = from c in myDoc.Descendants("Customer")
23                             select new Customer
24                             {
25                                 ID=c.FirstAttribute.Value,
26                                 UseName = c.Element("Usename").Value,
27                                 FirstName = c.Element("FirstName").Value,
28                                 LastName = c.Element("LastName").Value,
29                                 Phone = c.Element("PhoneNo").Value
30                             };
31                 foreach (var item in query)
32                 {
33                     listCs.Add(item);
34                 }
35             }
36             return listCs;
37         }

以上的Customer类的属性和xml文档节点内容相对应 Customer类如下

    public class Customer
    {
        public string ID { get; set; }
        public string UseName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
    }

3.向XML文档添加内容

        #region Insert new item
        public static void InsertNewElement(Customer cs)
        {
            try
            {
                // Load current document. 
                XDocument myDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
                Random r = new Random();
                // add new element 
                XElement newElement = new XElement("Customer",new XAttribute("ID", r.Next(5000)),
                          new XElement("Usename", cs.UseName),
                          new XElement("FirstName", cs.FirstName),
                          new XElement("LastName", cs.LastName),
                          new XElement("PhoneNo", cs.Phone));
                myDoc.Descendants("Customers").First().Add(newElement);
                // Save changes.
                myDoc.Save(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

4.修改XML文档内容

 1         public static void EditElement(Customer cs)
 2         {
 3             try
 4             {
 5                 // Load current document. 
 6                 XDocument myDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
 7                 //by ID load xml 
 8                 IEnumerable products = from c in myDoc.Descendants("Customer") where c.FirstAttribute.Value == cs.ID select c;
 9                 if (products.Count() > 0)
10                 {
11                     XElement product = products.First();
12                     //replace xml element
13                     product.ReplaceNodes( new XElement("Usename", cs.UseName), new XElement("FirstName", cs.FirstName), new XElement("LastName", cs.LastName), new XElement("PhoneNo", cs.Phone));
14                 }
15                 myDoc.Save(HttpContext.Current.Server.MapPath("~/Customer.xml"));
16             }
17             catch (Exception ex)
18             {
19                 throw ex;
20             }
21         }

5.删除XML文档节点

 1         public static void DeleteElement(string id)
 2         {
 3             try
 4             {
 5                 XDocument myDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
 6                 IEnumerable customer = from c in myDoc.Descendants("Customer") where c.FirstAttribute.Value == id select c;
 7                 if (customer.Count() > 0)
 8                 {
 9                     customer.First().Remove();
10                 }
11                 myDoc.Save(HttpContext.Current.Server.MapPath("~/Customer.xml"));
12             }
13             catch (Exception ex)
14             {
15                 throw ex;
16             }
17         }

6.通过指定值查询特定XML节点内容

 1         #region Query customer
 2         public static Customer FindCustomerByID(string id)
 3         {
 4             try
 5             {
 6                 Customer cs = new Customer();
 7                 // Load current document. 
 8                 XDocument myDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Customer.xml"));
 9                 var query = from c in myDoc.Root.Elements("Customer")
10                             where (string)c.FirstAttribute.Value == id
11                             select new Customer
12                             {
13                                 ID = c.FirstAttribute.Value,
14                                 UseName = c.Element("Usename").Value,
15                                 FirstName = c.Element("FirstName").Value,
16                                 LastName = c.Element("LastName").Value,
17                                 Phone = c.Element("PhoneNo").Value
18                             };
19 
20                 foreach (var item in query)
21                 {
22                     cs.ID = item.ID;
23                     cs.UseName = item.UseName;
24                     cs.FirstName = item.FirstName;
25                     cs.LastName = item.LastName;
26                     cs.Phone = item.Phone;
27                 }
28                 return cs;
29             }
30             catch (Exception ex)
31             {
32                 return null;
33             }
34         }
35         #endregion

7.结合以上方法做了一个MVC操作XML文档的增删改查的Demo 源码地址如下

https://github.com/ZedH/XmlTest

 

C#操作xml文档增删改查(Linq to XML)

标签:删除   each   sys   通过   catch   string   dom   结合   var   

原文地址:https://www.cnblogs.com/Zed-H/p/11074893.html


评论


亲,登录后才可以留言!