Reputation: 3
I have an XML file that has the following
All that I'm trying to do is display the text in a multi line textbox just as it is in the file. I've found the code on the Microsoft site and altered it slightly to work for me but I'm still not quite there.
<Employees>
<Employee>
<Name>Davolio, Nancy</Name>
<Title>Sales Representative</Title>
<BirthDay>12/08/1948</BirthDay>
<HireDate>05/01/1992</HireDate>
</Employee>
<Employee>
<Name>Fuller, Andrew</Name>
<Title>Vice President, Sales</Title>
<BirthDay>02/19/1952</BirthDay>
<HireDate>08/14/1992</HireDate>
</Employee>
<Employee>
<Name>Leverling, Janet</Name>
<Title>Sales Representative</Title>
<BirthDay>08/30/1963</BirthDay>
<HireDate>04/01/1992</HireDate>
</Employee>
Code:
XmlTextReader reader = new XmlTextReader("Employees.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.NodeType == System.Xml.XmlNodeType.Element)
contents += "<" + reader.Name + ">\n ";
if (reader.NodeType == System.Xml.XmlNodeType.Text)
contents += reader.Value + "</" + reader.Name+ ">\n";
}
//Console.Write(contents);
txtStats.Text = "File Creation Time = " + File.GetCreationTime(Server.MapPath("../XMLFiles/Employees.xml")).ToString()
+ "\n" + "File Last Access Time = " + File.GetLastAccessTime(Server.MapPath("../XMLFiles/Employees.xml")).ToString()
+ "\n" + "File Last Write Time = " + File.GetLastWriteTime(Server.MapPath("../XMLFiles/Employees.xml")).ToString()
+ "\n"
+ "\n"
+ contents.ToString();
This gets me the following.
<Employees>
<Employee>
<Name>
Davolio, Nancy</>
<Title>
Sales Representative</>
<BirthDay>
12/08/1948</>
<HireDate>
05/01/1992</>
<Employee>
<Name>
Fuller, Andrew</>
<Title>
Vice President, Sales</>
<BirthDay>
02/19/1952</>
<HireDate>
08/14/1992</>
<Employee>
<Name>
Leverling, Janet</>
<Title>
Sales Representative</>
<BirthDay>
08/30/1963</>
<HireDate>
04/01/1992</>
If there is a better way of doing this then I'm happy to hear of alternatives.
Upvotes: 0
Views: 241
Reputation: 103467
If you just want to display the file exactly as it is, then you don't need to parse it as xml. You can just use File.ReadAllText:
textBox1.Text = File.ReadAllText("Employees.xml");
Alternatively, if you wanted to format it, an easy way is to run it through an XDocument
, like this:
textBox1.Text = XDocument.Load("Employees.xml").ToString();
Upvotes: 1