0

我有一个包含以下内容的 XML 文件

我要做的就是在多行文本框中显示文本,就像在文件中一样。我在 Microsoft 网站上找到了代码,并对其稍作修改以适合我,但我仍然不完全在那里。

<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</>

如果有更好的方法可以做到这一点,那么我很高兴听到替代方案。

4

1 回答 1

1

如果您只想按原样显示文件,则无需将其解析为 xml。您可以只使用File.ReadAllText

textBox1.Text = File.ReadAllText("Employees.xml");

或者,如果您想对其进行格式化,一种简单的方法是通过 运行它XDocument,如下所示:

textBox1.Text = XDocument.Load("Employees.xml").ToString();
于 2013-07-07T04:25:40.237 回答