.NET: XML

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

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

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

 1 <?xml version="1.0" encoding="utf-8"?>

 2 <bookstore>

 3   <!--记录书本的信息-->

 4   <book Type="必修课" ISBN="7-11-19149-2">

 5     <title>数据结构</title>

 6     <author>严蔚敏</author>

 7     <price>30.00</price>

 8   </book>

 9   <book Type="必修课" ISBN="7-111-19149-3">

10     <title>路由型与交换型互联网基础</title>

11     <author>程青梅</author>

12     <price>27.00</price>

13   </book>

14   <book Type="必修课" ISBN="7-111-19149-4">

15     <title>计算机硬件技术基础</title>

16     <author>李基灿</author>

17     <price>25.00</price>

18   </book>

19   <book Type="必修课" ISBN="7-111-19149-5">

20     <title>软件质量保证与管理</title>

21     <author>朱少敏</author>

22     <price>39.00</price>

23   </book>

24   <book Type="必修课" ISBN="7-111-19149-6">

25     <title>算法设计与分析</title>

26     <author>王红梅</author>

27     <price>23.00</price>

28   </book>

29   <book Type="选修课" ISBN="7-111-19149-1">

30     <title>计算机操作系统</title>

31     <author>林美苏</author>

32     <price>28.00</price>

33   </book>

34 </bookstore>
View Code

再定义一个BookModel类

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 

 6 namespace ConsoleTest

 7 {

 8     public class BookModel

 9     {

10         public BookModel()

11         {

12         }

13 

14         private string bookType;

15         public string BookType

16         {

17             get { return bookType; }

18             set { bookType = value; }

19         }

20 

21         private string bookISBN;

22         public string BookISBN

23         {

24             get { return bookISBN; }

25             set { bookISBN = value; }

26         }

27 

28         private string bookName;

29         public string BookName

30         {

31             get { return bookName; }

32             set { bookName = value; }

33         }

34 

35         private string bookAuthor;

36         public string BookAuthor

37         {

38             get { return bookAuthor; }

39             set { bookAuthor = value; }

40         }

41 

42         private double bookPrice;

43         public double BookPrice

44         {

45             get { return bookPrice; }

46             set { bookPrice = value; }

47         }

48     }

49 }
View Code

1. XmlDocument

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

 2. 用XmlTextReader和XmlTextWriter

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

  1 using System;

  2 using System.Collections.Generic;

  3 using System.Linq;

  4 using System.Text;

  5 using System.Xml;

  6 using System.Xml.Linq;

  7 

  8 namespace ConsoleTest

  9 {

 10     public class Program

 11     {

 12         static private void showXmlInfo(string path)

 13         {

 14             XmlDocument doc = new XmlDocument();

 15             XmlReaderSettings settings = new XmlReaderSettings();

 16             settings.IgnoreComments = true;

 17             XmlReader reader = XmlReader.Create(path, settings);

 18             doc.Load(reader);

 19 

 20             XmlNode xn = doc.DocumentElement;

 21             XmlNodeList xnl = xn.ChildNodes;

 22             List<BookModel> bookModelList = new List<BookModel>();

 23             foreach (XmlNode xmlNode in xnl)

 24             {

 25                 BookModel bookModel = new BookModel();

 26                 XmlElement xe = (XmlElement)xmlNode;

 27                 bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();

 28                 bookModel.BookType = xe.GetAttribute("Type").ToString();

 29                 XmlNodeList xnlChild = xe.ChildNodes;

 30                 bookModel.BookName = xnlChild.Item(0).InnerText;

 31                 bookModel.BookAuthor = xnlChild.Item(1).InnerText;

 32                 bookModel.BookPrice = Convert.ToDouble(xnlChild.Item(2).InnerText);

 33                 bookModelList.Add(bookModel);

 34             }

 35             foreach (BookModel book in bookModelList)

 36             {

 37                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);

 38                 Console.WriteLine("\tBookName: {0}", book.BookName);

 39                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);

 40                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);

 41             }

 42             reader.Close();

 43         }

 44 

 45         static private void showXmlInfoByTextReader(string path)

 46         {

 47             XmlTextReader reader = new XmlTextReader(path);

 48             List<BookModel> modelList = new List<BookModel>();

 49             BookModel model = new BookModel();

 50             while (reader.Read())

 51             {

 52                 if (reader.NodeType == XmlNodeType.Element)

 53                 {

 54                     if (reader.Name == "book")

 55                     {

 56                         model.BookType = reader.GetAttribute(0);

 57                         model.BookISBN = reader.GetAttribute(1);

 58                     }

 59                     if (reader.Name == "title")

 60                     {

 61                         model.BookName = reader.ReadElementString().Trim();

 62                     }

 63                     if (reader.Name == "author")

 64                     {

 65                         model.BookAuthor = reader.ReadElementString().Trim();

 66                     }

 67                     if (reader.Name == "price")

 68                     {

 69                         model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());

 70                     }

 71                 }

 72                 if (reader.NodeType == XmlNodeType.EndElement)

 73                 {

 74                     modelList.Add(model);

 75                     model = new BookModel();

 76                 }

 77             }

 78             modelList.RemoveAt(modelList.Count - 1);

 79             foreach (BookModel book in modelList)

 80             {

 81                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);

 82                 Console.WriteLine("\tBookName: {0}", book.BookName);

 83                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);

 84                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);

 85             }

 86             reader.Close();

 87         }

 88 

 89         static void Main(string[] args)

 90         {

 91             const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

 92 

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

 94             showXmlInfo(PATH);

 95 

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

 97             showXmlInfoByTextReader(PATH);

 98 

 99             XmlDocument doc = new XmlDocument();

100             doc.Load(PATH);

101             XmlNode root = doc.DocumentElement;

102 

103             XmlElement xelKey = doc.CreateElement("book");

104             xelKey.SetAttribute("Type", "选修课");

105             xelKey.SetAttribute("ISBN", "7-111-19149-7");

106 

107             XmlElement xelTitle = doc.CreateElement("title");

108             xelTitle.InnerText = "计算机算法与结构";

109             XmlElement xelAuthor = doc.CreateElement("author");

110             xelAuthor.InnerText = "程晓旭";

111             XmlElement xelPrice = doc.CreateElement("price");

112             xelPrice.InnerText = "50.00";

113             xelKey.AppendChild(xelTitle);

114             xelKey.AppendChild(xelAuthor);

115             xelKey.AppendChild(xelPrice);

116 

117             root.AppendChild(xelKey);

118             doc.Save(PATH);

119             Console.WriteLine("\nApending one child by XmlDocument...\n");

120             showXmlInfo(PATH);

121 

122             xelKey.GetElementsByTagName("title").Item(0).InnerText = ".NET深入浅出";

123             xelKey.GetElementsByTagName("author").Item(0).InnerText = "冯小兵";

124             xelKey.GetElementsByTagName("price").Item(0).InnerText = "49.00";

125             doc.Save(PATH);

126 

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

128             showXmlInfo(PATH);

129 

130             xelKey.ParentNode.RemoveChild(xelKey);

131             doc.Save(PATH);

132             Console.WriteLine("\nRemove one child...\n");

133             showXmlInfo(PATH);

134         }

135     }

136 }
View Code

用windowsForm的listBox来显示的时候

 1 using System;

 2 using System.Collections.Generic;

 3 using System.ComponentModel;

 4 using System.Data;

 5 using System.Drawing;

 6 using System.Linq;

 7 using System.Text;

 8 using System.Windows.Forms;

 9 using System.Xml;

10 

11 namespace WindowsTest

12 {

13     public partial class Form1 : Form

14     {

15         const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

16         public Form1()

17         {

18             InitializeComponent();

19         }

20 

21         private void Form1_Load(object sender, EventArgs e)

22         {

23             XmlDocument doc = new XmlDocument();

24             doc.Load(PATH);

25             RecurseXmlDocument((XmlNode)doc.DocumentElement, 0);

26         }

27 

28         private void RecurseXmlDocument(XmlNode root, int indent)

29         {

30             if (root == null) return;

31             if (root is XmlElement)

32             {

33                 listBox1.Items.Add(root.Name.PadLeft(root.Name.Length + indent));

34                 if (root.HasChildNodes)

35                 {

36                     RecurseXmlDocument(root.FirstChild, indent + 2);

37                 }

38 

39                 if (root.NextSibling != null)

40                 {

41                     RecurseXmlDocument(root.NextSibling, indent);

42                 }

43                     

44             }

45             else if (root is XmlText)

46             {

47                 string text = ((XmlText)root).Value;

48                 listBox1.Items.Add(text.PadLeft(text.Length + indent));

49             }

50         }

51     }

52 }
View Code

 

3. 用LINQ

3.0的新发现

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 using System.Xml;

 6 using System.Xml.Linq;

 7 

 8 namespace ConsoleTest

 9 {

10     public class Program

11     {

12         static private void showXmlInfoByLinq(string path)

13         {

14             XElement xe = XElement.Load(path);

15             IEnumerable<XElement> elements = from ele in xe.Elements("book")

16                                              select ele;

17             List<BookModel> modelList = new List<BookModel>();

18             foreach (var ele in elements)

19             {

20                 BookModel model = new BookModel();

21                 model.BookAuthor = ele.Element("author").Value;

22                 model.BookName = ele.Element("title").Value;

23                 model.BookPrice = Convert.ToDouble(ele.Element("price").Value);

24                 model.BookISBN = ele.Attribute("ISBN").Value;

25                 model.BookType = ele.Attribute("Type").Value;

26                 modelList.Add(model);

27             }

28             foreach (BookModel book in modelList)

29             {

30                 Console.WriteLine("Book ISBN: {0}   Type: {1}", book.BookISBN, book.BookType);

31                 Console.WriteLine("\tBookName: {0}", book.BookName);

32                 Console.WriteLine("\tBookAuthor: {0}", book.BookAuthor);

33                 Console.WriteLine("\tBookPrice: {0}", book.BookPrice);

34             }

35         }

36 

37         static void Main(string[] args)

38         {

39             const string PATH = @"C:\Users\Administrator\Desktop\Demo\Book.XML";

40 

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

42             showXmlInfoByLinq(PATH);

43 

44             XElement xe = XElement.Load(PATH);

45             XElement record = new XElement(

46                 new XElement("book",

47                     new XAttribute("Type", "选修课"),

48                     new XAttribute("ISBN", "7-111-19149-8"),

49                     new XElement("title", "敏捷开发"),

50                     new XElement("author", "秦朗"),

51                     new XElement("price", 34.00)

52                     )

53                 );

54             xe.Add(record);

55             xe.Save(PATH);

56             Console.WriteLine("\nApending one child by XmlLinq...\n");

57             showXmlInfoByLinq(PATH);

58 

59             xe = XElement.Load(PATH);

60             IEnumerable<XElement> element = from ele in xe.Elements("book")

61                                             where ele.Attribute("ISBN").Value == "7-111-19149-8"

62                                             select ele;

63             if (element.Count() > 0)

64             {

65                 XElement first = element.First();

66                 first.SetAttributeValue("Type", "必修课");

67                 first.ReplaceNodes(

68                     new XElement("title", "敏捷开发框架"),

69                     new XElement("author", "秦明"),

70                     new XElement("price", 35.00)

71                     );

72             }

73             xe.Save(PATH);

74             Console.WriteLine("\nEditting one child by XmlLinq...\n");

75             showXmlInfoByLinq(PATH);

76 

77             xe = XElement.Load(PATH);

78             IEnumerable<XElement> elements = from ele in xe.Elements("book")

79                                              where ele.Attribute("ISBN").Value == "7-111-19149-8"

80                                              select ele;

81             if (elements.Count() > 0)

82             {

83                 elements.First().Remove();

84             }

85             xe.Save(PATH);

86             Console.WriteLine("\nRemoving one child by XmlLinq...\n");

87             showXmlInfoByLinq(PATH);

88         }

89     }

90 }
View Code

 

你可能感兴趣的:(.net)