了解XML
XML
命名空间: Using System.Xml;
程序集: System.Xml(在System.Xml.dll中)
涉及到的类和方法:
XmlDeclaration 类:表示 XML 声明节点:<?xml version='1.0'...?>,XML文件第一行。
XmlDocument 类:表示 XML 文档。 可使用此类在文档中加载、验证、编辑、添加和放置 XML。
CreateElement 方法 (String, String, String):创建具有指定 Prefix、LocalName 和 NamespaceURI 的元素。
Prefix:新元素的前缀(如果有的话)。
LocalName:新元素的本地名称。
NamespaceURI:新元素的命名空间 URI(如果有的话)。
XmlElement 类:表示元素。
XmlNode 类:表示 XML 文档中的单个节点。
AppendChild方法:将指定的节点添加到该节点的子节点列表的末尾。
SelectSingleNode方法:选择第一个 XmlNode ,与 XPath 表达式匹配。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <User> 3 <root student.Name="祥妹妹" student.Age="25"> 4 <Name>祥妹妹</Name> 5 <Age>25</Age> 6 <Class>1702B</Class> 7 </root> 8 </User>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Xml; 7 8 namespace a 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 15 16 Student student = new Student(); 17 student.Name = "祥妹妹"; 18 student.Age = 25; 19 20 21 22 23 24 //创建XmlDocument对象 25 //XmlDocument 表示XML文档可使用此类在文档中加载、验证、编辑、添加和放置 XML 26 XmlDocument xmlDoc = new XmlDocument(); 27 28 //XML的声明<?xml version="1.0" encoding="gb2312"?> 29 //声明后的数据,表示XML的开头 <?xml version="1.0" encoding="UTF-8"?> 30 XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); 31 32 //追加xmldecl位置 33 xmlDoc.AppendChild(xmlSM); 34 //添加一个名为User的根节点 35 XmlElement xml = xmlDoc.CreateElement("", "User", ""); 36 //追加User的根节点位置 37 xmlDoc.AppendChild(xml); 38 //添加另一个节点,与User所匹配,查找<User> 39 XmlNode User = xmlDoc.SelectSingleNode("User"); 40 //添加一个名为<root>的节点 41 XmlElement root = xmlDoc.CreateElement("root"); 42 //为<root>节点的属性 43 root.SetAttribute("student.Name", $"{student.Name}"); 44 root.SetAttribute("student.Age", $"{student.Age}"); 45 46 //添加一名为Name元素 47 XmlElement x1 = xmlDoc.CreateElement("Name"); 48 //InnerText:获取或设置节点及其所有子节点的串连值 49 x1.InnerText = $"{student.Name}"; 50 root.AppendChild(x1);//添加到<Zi>节点中 51 52 //添加一名为Age元素 53 XmlElement x2 = xmlDoc.CreateElement("Age"); 54 x2.InnerText = $"{student.Age}"; 55 root.AppendChild(x2); 56 57 //添加一名为Class元素 58 XmlElement x3 = xmlDoc.CreateElement("Class"); 59 x3.InnerText = "1702B"; 60 root.AppendChild(x3); 61 62 //添加到<User>节点中 63 User.AppendChild(root); 64 //保存好创建的XML文档 65 xmlDoc.Save(@"E:课程总练习MVCaXMLFile1.xml"); 66 67 Console.WriteLine(save_abc()); 68 69 70 Console.ReadKey(); 71 } 72 73 public static string save_abc() 74 { 75 string abc = System.IO.File.ReadAllText(@"E:课程总练习MVCaXMLFile1.xml"); 76 77 string str = "<Student><StudentNumber>123456</StudentNumber><StudentName>Hannes</StudentName></Student>"; 78 return abc; 79 } 80 } 81 } 82 83 84 85 using System; 86 using System.Collections.Generic; 87 using System.Linq; 88 using System.Text; 89 using System.Threading.Tasks; 90 91 namespace a 92 { 93 public class Student 94 { 95 public string Name { get; set; } 96 public int Age { get; set; } 97 } 98 }