1. 程式人生 > >C# xml讀寫

C# xml讀寫

document path nodetype public oot art ade appdomain sed

 1 class XmlClass
 2     {
 3         public string Pathname; //總列表
 4         public XmlClass()
 5         {
 6             string str = System.AppDomain.CurrentDomain.BaseDirectory;
 7             string path = str;
 8             
 9             for (int i = 0; i < 3; i++)
10             {
11                 string
rootpath = path.Substring(0, path.LastIndexOf("\\")); 12 path = rootpath; 13 } 14 Pathname = path + "\\Document\\myxml.xml"; 15 } 16 17 public string[] XmlStore() 18 { 19 string []elements = new string[2]; 20 XmlReader reader = XmlReader.Create(Pathname);
21 22 while (reader.Read()) 23 { 24 if (reader.NodeType == XmlNodeType.Element) //如果是開始節點 25 { 26 switch (reader.Name) 27 { 28 case "Meet": 29 {
30 if (reader.Value == "") 31 elements[0] = (string)reader.ReadElementContentAs(typeof(string), null);
//適用父節點包含單個子元素,否則其余子元素無法獲取
32 else 33 elements[0] = reader.ReadContentAsString(); 34 }break; 35 36 case "Topic": 37 { 38 if (reader.Value == "") 39 elements[1] = (string)reader.ReadElementContentAs(typeof(string), null); 40 else 41 elements[1] = reader.ReadContentAsString(); 42 }break; 43 default: 44 break; 45 } 46 } 47 } 48 reader.Close(); 49 reader.Dispose(); 50 return elements; 51 } 52 53 public void XmlDisplay(string metting, string topic) 54 { 55 using (FileStream fs = new FileStream(Pathname, FileMode.Create, FileAccess.Write)) 56 { 57 XmlWriter writer = XmlWriter.Create(fs); 58 writer.WriteStartElement("Root"); 59 60 writer.WriteStartElement("Root1"); 61 writer.WriteElementString("Meet", metting); 62 writer.WriteEndElement(); 63 64 writer.WriteStartElement("Root2"); 65 writer.WriteElementString("Topic", topic); 66 writer.WriteEndElement(); 67 writer.WriteEndElement(); 68 writer.Close(); 69 writer.Dispose(); 70 } 71 } 72 }

C# xml讀寫