使用Linq对XML进行增删查改

前端之家收集整理的这篇文章主要介绍了使用Linq对XML进行增删查改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 引入 命名空间

using System.Xml.Linq;

2. Xml的结构


<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product Id="1">
    <Name>HTC One</Name>
    <Price>4856.23</Price>
    <Count>100</Count>
  </Product>
  <Product Id="2">
    <Name>Iphone 6 Update</Name>
    <Price>5856.23</Price>
    <Count>655</Count>
  </Product>
  <Product Id="3">
    <Name>Lenno K800</Name>
    <Price>3856.23</Price>
    <Count>898</Count>
  </Product>
  <Product Id="4">
    <Name>HuaWei P7</Name>
    <Price>2856.23</Price>
    <Count>1000</Count>
  </Product>
  <Product Id="5">
    <Name>MI 4</Name>
    <Price>1856.23</Price>
    <Count>1</Count>
  </Product>
</Products>

3. 后台程序


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

using System.Xml.Linq;

namespace XMLLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            string Path = AppDomain.CurrentDomain.BaseDirectory;
            string xmlPath = System.IO.Path.Combine(Path,"../../Product.xml");

           XElement xmlDoc = XElement.Load(xmlPath);


           //1.取所有节点的数据

           IEnumerable<XElement> xmlCollection = xmlDoc.Elements("Product");

           Console.WriteLine("Count:"+xmlCollection.Count());

           var linq = from x in xmlCollection select new {Name=x.Element("Name").Value,Price = x.Element("Price").Value,Count=x.Element("Count").Value};

            foreach(var e in linq){
            Console.WriteLine("Name={0},Price={1},Count={2}",e.Name,e.Price,e.Count);
            }


            //2. 取某一个节点
            Console.WriteLine("One Record:");
            var oneObj = xmlCollection.Where(x => x.Attribute("Id").Value.Equals("2")).First();
            Console.WriteLine("Name={0},oneObj.Element("Name").Value,oneObj.Element("Price").Value,oneObj.Element("Count").Value);
          

            //3. 新增一个节点
            XElement newElement = new XElement(
                "Product",new XAttribute("Id",xmlCollection.Count()+1),new XElement("Name","new Product"),new XElement("Price",new decimal(100)),new XElement("Count",200)
                );

            xmlDoc.Add(newElement);
            xmlDoc.Save(xmlPath);

            //修改节点的值
            Console.WriteLine("Upldate Record:");
            var UpdateObj = xmlCollection.Where(x => x.Attribute("Id").Value.Equals("2")).First();
            UpdateObj.SetElementValue("Name","Iphone 6 Update");
            xmlDoc.Save(xmlPath);

            //删除一个节点

            Console.WriteLine("Delete Record:");
            var deleteObj = xmlCollection.Where(x => x.Attribute("Id").Value.Equals("6")).FirstOrDefault();
            if(null != deleteObj){
             deleteObj.Remove();
             xmlDoc.Save(xmlPath);
            }
           
          


            Console.ReadLine();
        }
    }
}

猜你在找的XML相关文章