我有一个XML文件,其中包含以下内容
我要做的就是在多行文本框中显示文本,就像在文件中一样。我在微软网站上找到了代码,稍微改了一下,对我有用,但我还是不太适合。
<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>
代码:
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();
这让我得到以下结论。
<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</>
如果有更好的方法,那么我很高兴听到其他选择。
答案 0 :(得分:1)
如果您只想完全按原样显示文件,则无需将其解析为xml。您可以使用File.ReadAllText:
textBox1.Text = File.ReadAllText("Employees.xml");
或者,如果您想格式化它,一种简单的方法是通过XDocument
运行它,如下所示:
textBox1.Text = XDocument.Load("Employees.xml").ToString();