2013-07-07 71 views
-1

我有具有以下讀取XML文件,只是因爲它是

所有我想要做的是顯示在多行文本框,就像它是文件中的文本的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</> 

如果有更好的方法做到這一點,那麼我很樂意聽到替代方案。

+1

爲什麼不直接用'文件中加載.ReadAllText'?你似乎不在乎它是xml。 – Blorgbeard

+1

或者你可以'XDocument.Load(filename).ToString()'如果你想自動格式化它 – Blorgbeard

回答

1

如果您只是想按照原樣顯示文件,則無需將其解析爲xml。你可以只用File.ReadAllText

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

另外,如果你想格式化,一個簡單的方法是通過XDocument來運行它,就像這樣:

textBox1.Text = XDocument.Load("Employees.xml").ToString(); 
+0

Blorgbeard,XDocument.Load(filename).ToString()訣竅。我沒有意識到這很容易,我搜索了幾天,並沒有找到任何答案遠程輕鬆。非常感謝。 – user2557462