XML在平常生活中用得很多,它的结构很简单,跟windows explorer有点像。

对它进行操作主要有三种方式:XmlDocument,

假设有这么一个XML文件Book.XML

 <?xml version="1.0" encoding="utf-8"?>
 <bookstore>
   <!--记录书本的信息-->
   <book Type="必修课" ISBN="7-11-19149-2">
     <title>数据结构</title>
     <author>严蔚敏</author>
     <price>30.00</price>
   </book>
   <book Type="必修课" ISBN="7-111-19149-3">
     <title>路由型与交换型互联网基础</title>
     <author>程青梅</author>
     <price>27.00</price>
   </book>
   <book Type="必修课" ISBN="7-111-19149-4">
     <title>计算机硬件技术基础</title>
     <author>李基灿</author>
     <price>25.00</price>
   </book>
   <book Type="必修课" ISBN="7-111-19149-5">
     <title>软件质量保证与管理</title>
     <author>朱少敏</author>
     <price>39.00</price>
   </book>
   <book Type="必修课" ISBN="7-111-19149-6">
     <title>算法设计与分析</title>
     <author>王红梅</author>
     <price>23.00</price>
   </book>
   <book Type="选修课" ISBN="7-111-19149-1">
     <title>计算机操作系统</title>
     <author>林美苏</author>
     <price>28.00</price>
   </book>
 </bookstore>

再定义一个BookModel类

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

 namespace ConsoleTest
 {
     public class BookModel
     {
         public BookModel()
         {
         }

         private string bookType;
         public string BookType
         {
             get { return bookType; }
             set { bookType = value; }
         }

         private string bookISBN;
         public string BookISBN
         {
             get { return bookISBN; }
             set { bookISBN = value; }
         }

         private string bookName;
         public string BookName
         {
             get { return bookName; }
             set { bookName = value; }
         }

         private string bookAuthor;
         public string BookAuthor
         {
             get { return bookAuthor; }
             set { bookAuthor = value; }
         }

         private double bookPrice;
         public double BookPrice
         {
             get { return bookPrice; }
             set { bookPrice = value; }
         }
     }
 }

1. XmlDocument

分别演示了读取,增加,修改和删除

2. 用XmlTextReader和XmlTextWriter

XmlTextWriter要覆盖原来的文件,显得很麻烦,这里就不写了

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

 namespace ConsoleTest
 {
     public class Program
     {
         static private void showXmlInfo(string path)
         {
             XmlDocument doc = new XmlDocument();
             XmlReaderSettings settings = new XmlReaderSettings();
             settings.IgnoreComments = true;
             XmlReader reader = XmlReader.Create(path, settings);
             doc.Load(reader);

             XmlNode xn = doc.DocumentElement;
             XmlNodeList xnl = xn.ChildNodes;
             List<BookModel> bookModelList = new List<BookModel>();
             foreach (XmlNode xmlNode in xnl)
             {
                 BookModel bookModel = new BookModel();
                 XmlElement xe = (XmlElement)xmlNode;
                 bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
                 bookModel.BookType = xe.GetAttribute("Type").ToString();
                 XmlNodeList xnlChild = xe.ChildNodes;
                 bookModel.BookName = xnlChild.Item().InnerText;
                 bookModel.BookAuthor = xnlChild.Item().InnerText;
                 bookModel.BookPrice = Convert.ToDouble(xnlChild.Item().InnerText);
                 bookModelList.Add(bookModel);
             }
             foreach (BookModel book in bookModelList)
             {
                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);
                 Console.WriteLine("\tBookName: {0}", book.BookName);
                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);
                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);
             }
             reader.Close();
         }

         static private void showXmlInfoByTextReader(string path)
         {
             XmlTextReader reader = new XmlTextReader(path);
             List<BookModel> modelList = new List<BookModel>();
             BookModel model = new BookModel();
             while (reader.Read())
             {
                 if (reader.NodeType == XmlNodeType.Element)
                 {
                     if (reader.Name == "book")
                     {
                         model.BookType = reader.GetAttribute();
                         model.BookISBN = reader.GetAttribute();
                     }
                     if (reader.Name == "title")
                     {
                         model.BookName = reader.ReadElementString().Trim();
                     }
                     if (reader.Name == "author")
                     {
                         model.BookAuthor = reader.ReadElementString().Trim();
                     }
                     if (reader.Name == "price")
                     {
                         model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());
                     }
                 }
                 if (reader.NodeType == XmlNodeType.EndElement)
                 {
                     modelList.Add(model);
                     model = new BookModel();
                 }
             }
             modelList.RemoveAt(modelList.Count - );
             foreach (BookModel book in modelList)
             {
                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);
                 Console.WriteLine("\tBookName: {0}", book.BookName);
                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);
                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);
             }
             reader.Close();
         }

         static void Main(string[] args)
         {
             const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

             Console.WriteLine("Read by XmlDocument...\n");
             showXmlInfo(PATH);

             Console.WriteLine("\nRead by XmlTextReader...\n");
             showXmlInfoByTextReader(PATH);

             XmlDocument doc = new XmlDocument();
             doc.Load(PATH);
             XmlNode root = doc.DocumentElement;

             XmlElement xelKey = doc.CreateElement("book");
             xelKey.SetAttribute("Type", "选修课");
             xelKey.SetAttribute("ISBN", "7-111-19149-7");

             XmlElement xelTitle = doc.CreateElement("title");
             xelTitle.InnerText = "计算机算法与结构";
             XmlElement xelAuthor = doc.CreateElement("author");
             xelAuthor.InnerText = "程晓旭";
             XmlElement xelPrice = doc.CreateElement("price");
             xelPrice.InnerText = "50.00";
             xelKey.AppendChild(xelTitle);
             xelKey.AppendChild(xelAuthor);
             xelKey.AppendChild(xelPrice);

             root.AppendChild(xelKey);
             doc.Save(PATH);
             Console.WriteLine("\nApending one child by XmlDocument...\n");
             showXmlInfo(PATH);

             xelKey.GetElementsByTagName().InnerText = ".NET深入浅出";
             xelKey.GetElementsByTagName().InnerText = "冯小兵";
             xelKey.GetElementsByTagName().InnerText = "49.00";
             doc.Save(PATH);

             Console.WriteLine("\nEditting one child...\n");
             showXmlInfo(PATH);

             xelKey.ParentNode.RemoveChild(xelKey);
             doc.Save(PATH);
             Console.WriteLine("\nRemove one child...\n");
             showXmlInfo(PATH);
         }
     }
 }

用windowsForm的listBox来显示的时候

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using System.Xml;

 namespace WindowsTest
 {
     public partial class Form1 : Form
     {
         const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";
         public Form1()
         {
             InitializeComponent();
         }

         private void Form1_Load(object sender, EventArgs e)
         {
             XmlDocument doc = new XmlDocument();
             doc.Load(PATH);
             RecurseXmlDocument((XmlNode)doc.DocumentElement, );
         }

         private void RecurseXmlDocument(XmlNode root, int indent)
         {
             if (root == null) return;
             if (root is XmlElement)
             {
                 listBox1.Items.Add(root.Name.PadLeft(root.Name.Length + indent));
                 if (root.HasChildNodes)
                 {
                     RecurseXmlDocument(root.FirstChild, indent + );
                 }

                 if (root.NextSibling != null)
                 {
                     RecurseXmlDocument(root.NextSibling, indent);
                 }

             }
             else if (root is XmlText)
             {
                 string text = ((XmlText)root).Value;
                 listBox1.Items.Add(text.PadLeft(text.Length + indent));
             }
         }
     }
 }

3. 用LINQ

3.0的新发现

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

 namespace ConsoleTest
 {
     public class Program
     {
         static private void showXmlInfoByLinq(string path)
         {
             XElement xe = XElement.Load(path);
             IEnumerable<XElement> elements = from ele in xe.Elements("book")
                                              select ele;
             List<BookModel> modelList = new List<BookModel>();
             foreach (var ele in elements)
             {
                 BookModel model = new BookModel();
                 model.BookAuthor = ele.Element("author").Value;
                 model.BookName = ele.Element("title").Value;
                 model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
                 model.BookISBN = ele.Attribute("ISBN").Value;
                 model.BookType = ele.Attribute("Type").Value;
                 modelList.Add(model);
             }
             foreach (BookModel book in modelList)
             {
                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);
                 Console.WriteLine("\tBookName: {0}", book.BookName);
                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);
                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);
             }
         }

         static void Main(string[] args)
         {
             const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

             Console.WriteLine("\nRead by XmlLinq...\n");
             showXmlInfoByLinq(PATH);

             XElement xe = XElement.Load(PATH);
             XElement record = new XElement(
                 new XElement("book",
                     new XAttribute("Type", "选修课"),
                     new XAttribute("ISBN", "7-111-19149-8"),
                     new XElement("title", "敏捷开发"),
                     new XElement("author", "秦朗"),
                     new XElement("price", 34.00)
                     )
                 );
             xe.Add(record);
             xe.Save(PATH);
             Console.WriteLine("\nApending one child by XmlLinq...\n");
             showXmlInfoByLinq(PATH);

             xe = XElement.Load(PATH);
             IEnumerable<XElement> element = from ele in xe.Elements("book")
                                             where ele.Attribute("ISBN").Value == "7-111-19149-8"
                                             select ele;
             )
             {
                 XElement first = element.First();
                 first.SetAttributeValue("Type", "必修课");
                 first.ReplaceNodes(
                     new XElement("title", "敏捷开发框架"),
                     new XElement("author", "秦明"),
                     new XElement("price", 35.00)
                     );
             }
             xe.Save(PATH);
             Console.WriteLine("\nEditting one child by XmlLinq...\n");
             showXmlInfoByLinq(PATH);

             xe = XElement.Load(PATH);
             IEnumerable<XElement> elements = from ele in xe.Elements("book")
                                              where ele.Attribute("ISBN").Value == "7-111-19149-8"
                                              select ele;
             )
             {
                 elements.First().Remove();
             }
             xe.Save(PATH);
             Console.WriteLine("\nRemoving one child by XmlLinq...\n");
             showXmlInfoByLinq(PATH);
         }
     }
 }

.NET: XML的更多相关文章

  1. XStream将java对象转换为xml时,对象字段中的下划线“_”,转换后变成了两个的解决办法

            在前几天的一个项目中,由于数据库字段的命名原因 其中有两项:一项叫做"市场价格"一项叫做"商店价格" 为了便于区分,遂分别将其命名为market ...

  2. .NET Core采用的全新配置系统[9]: 为什么针对XML的支持不够好?如何改进?

    物理文件是我们最常用到的原始配置的载体,最佳的配置文件格式主要由三种,它们分别是JSON.XML和INI,对应的配置源类型分别是JsonConfigurationSource.XmlConfigura ...

  3. WebApi接口 - 响应输出xml和json

    格式化数据这东西,主要看需要的运用场景,今天和大家分享的是webapi格式化数据,这里面的例子主要是输出json和xml的格式数据,测试用例很接近实际常用情况:希望大家喜欢,也希望各位多多扫码支持和点 ...

  4. XML技术之DOM4J解析器

    由于DOM技术的解析,存在很多缺陷,比如内存溢出,解析速度慢等问题,所以就出现了DOM4J解析技术,DOM4J技术的出现大大改进了DOM解析技术的缺陷. 使用DOM4J技术解析XML文件的步骤? pu ...

  5. UWP开发之Mvvmlight实践六:MissingMetadataException解决办法(.Net Native下Default.rd.xml配置问题)

    最近完成一款UWP应用,在手机端测试发布版(Release)的时候应用莫名奇妙的强行关闭,而同样的应用包在PC端一点问题都没有,而且Debug版在两个平台都没有问题,唯独手机的Release版有问题. ...

  6. PHP中遍历XML之SimpleXML

    简单来讲述一些XML吧,XML是可扩展标记语言,是一种用于标记电子文件使其具有结构性的标记语言.XML是当今用于传输数据的两大工具之一,另外一个是json. 我们在PHP中使用XML也是用来传输数据, ...

  7. Asp.Net 操作XML文件的增删改查 利用GridView

    不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...

  8. Mybatis XML配置

    Mybatis常用带有禁用缓存的XML配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...

  9. Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)

    Android XML shape 标签使用详解   一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...

  10. C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素”

    Q: 在反序列化 Xml 字符串为 Xml 对象时,抛出如下异常. 即在 XML文档(0, 0)中有一个错误:缺少根元素. A: 首先看下代码: StringBuilder sb = new Stri ...

随机推荐

  1. vm设置静态ip

    1. 进入虚拟linux系统中,vim /etc/sysconfig/network-scripts/ifcfg-eth0,里面保留以下内容即可: DEVICE=eth0 //使用的网卡标识 BOOT ...

  2. 将真彩色转换成增强色的方法(即RGB32位或RGB24位颜色转换成RGB16位颜色的函数)

    今天由于程序需要,需要将真彩色转换成增强色进行颜色匹配,上网搜了一下没搜到相应函数,于是研究了一下RGB16位的增强色,写了这个函数: public static int RGB16(int argb ...

  3. 怎么用sql语句查询一个数据库有多少张表

    今天在技术群中闲谈时忽然聊到一个问题,那就是当一个数据库中有多张表时怎么快速的获取到表的个数,从而给问询者一个准确的回答. 大家或许会说,这个问题和我们的数据库操作没有太大关系或者不是很挂钩,所以没意 ...

  4. ArcGIS API for Silverlight 调用GP服务绘制等值面

    原文:ArcGIS API for Silverlight 调用GP服务绘制等值面 GP服务模型如下图: 示例效果图片如下:

  5. [LeetCode]题解(python):102 Binary Tree Level Order Traversal

    题目来源 https://leetcode.com/problems/binary-tree-level-order-traversal/ Given a binary tree, return th ...

  6. JS之mouseover和mouseenter

    mouseenter事件只会触发一次,触发对象是注册对象或者注册对象的子元素 mouseover事件可以触发多次,触发对象是注册对象或者注册对象的子元素 <!DOCTYPE html> & ...

  7. Sql Server中通配符

    Sql Server中通配符的使用 通配符_ "_"号表示任意单个字符,该符号只能匹配一个字符."_"可以放在查询条件的任意位置,且只能代表一个字符.一个汉字只 ...

  8. 如何查看mysql版本

    查到大概有5种,5.6.20就是版本号 1:在终端下:mysql -V. 以下是代码片段: 2:在mysql中:mysql> status;以下是代码片段: 3:在help里面查找,以下是代码片 ...

  9. 移动端省际联动插件mobiscroll

    <link href="assets/css/mobiscroll.custom-2.17.0.min.css" rel="stylesheet" typ ...

  10. WPF基础知识、界面布局及控件Binding

    WPF是和WinForm对应的,而其核心是数据驱动事件,在开发中显示的是UI界面和逻辑关系相分离的一种开放语言.UI界面是在XAML语言环境下开发人员可以进行一些自主设计的前台界面,逻辑关系还是基于c ...