To Examples
WriteReadXml Example, source code file Write.cs
using System; using System.Text; using System.IO; using System.Xml; namespace WriteReadXml { public class Write { public static void Main() { // Create XmlTextWriter object. XmlTextWriter w = new XmlTextWriter("../../persons.xml", null); // Create StreamReader object. StreamReader r = new StreamReader("../../persons.txt"); // Declare variables for inputs. string line, name, gender, age; string[] fields; // w.Formatting = Formatting.Indented; w.IndentChar = ' '; // Write start element for root. w.WriteStartElement("Persons"); while (r.Peek() != -1) { // Read line from input file. line = r.ReadLine(); fields = line.Split(','); name = fields[0]; gender = fields[1]; age = fields[2]; // Write Person element. w.WriteStartElement("Person"); w.WriteElementString("Name", name); w.WriteElementString("Gender", gender); w.WriteElementString("Age", age); w.WriteEndElement(); } // Write end element for root. w.WriteEndElement(); // Close writer. w.Close(); } } }
WriteReadXml Example, source code file Read.cs
using System; using System.Text; using System.IO; using System.Xml; namespace WriteReadXml { public class Read { public static void Main() { // Declare XmlTextReader. XmlTextReader r = new XmlTextReader("../../persons.xml"); // Declare StreamWriter. StreamWriter w = new StreamWriter("../../persons2.txt"); int count = 1; while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: if (r.Name == "Persons") { } else if (r.Name == "Person") { w.Write("Person {0}: ", count++); } else if (r.Name == "Name" || r.Name == "Gender" || r.Name == "Age") { w.Write(r.Name + ": " + " "); } break; case XmlNodeType.Text: w.Write(r.Value); break; case XmlNodeType.EndElement: if (r.Name == "Person") { w.WriteLine(); } else if (r.Name == "Persons") { } else { w.Write(" "); } break; } } // Close writer. w.Close(); } } }