2012-03-30 37 views
-1

認爲我的源文件看起來像這樣。如何讀取XML文檔並在c中顯示字符串輸出#

 <Content xmlns="uuid:4522eb85-0a47-45f9-8e2b-1x82c78xx920"> 
      <first>Hello World.This is Fisrt field</first> 
      <second>Hello World.This is second field</second> 
    </Content> 

我想寫一個代碼,它從一個位置讀取這個xml文檔並將其顯示爲字符串。

say name of the xml file is helloworld.xml. 
    Location: D:\abcd\cdef\all\helloworld.xml. 

我試過以下,但我無法做到這一點。

  XmlDocument contentxml = new XmlDocument(); 
      contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml"); 
      Response.Write("<BR>" + contentxml.ToString()); 

Response.write沒有顯示任何內容。糾正我,如果我錯過了任何事情。它沒有創建任何組件,錯誤即將到來。

我也試過,

  XmlDocument contentxml = new XmlDocument(); 
      try 
      { 
       contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml"); 
      } 
      catch (XmlException exp) 
      { 
       Console.WriteLine(exp.Message); 
      } 
      StringWriter sw = new StringWriter(); 
      XmlTextWriter xw = new XmlTextWriter(sw); 
      contentxml.WriteTo(xw); 
      Response.Write("<BR>" + sw.ToString()); 

,但我沒有找到任何輸出。

我想從一個位置讀取一個XML文件,並以字符串形式顯示它。

任何人都可以幫忙。

謝謝, Muzimil。

回答

4

您需要OuterXml屬性:

Response.Write("<BR>" + contentxml.OuterXml); 

而且您是要裝入文件不是XML所以使用

contentxml.Load(@"D:\abcd\cdef\all\helloworld.xml"); 

代替

contentxml.LoadXml(@"D:\abcd\cdef\all\helloworld.xml"); 
0

試試這個

XmlTextReader reader = new XmlTextReader (@"D:\abcd\cdef\all\helloworld.xml"); 
while (reader.Read()) 
{ 
    Console.WriteLine(reader.Name); 
} 
Console.ReadLine(); 
1

你真的要在所有反序列化XML?爲什麼不把它作爲文本文件讀取?喜歡的東西..

String text = File.ReadAllText(@"D:\abcd\cdef\all\helloworld.xml"); 
Response.Write(text); 

有了相應的錯誤處理明顯..

1

我會嘗試使用XDocument類:

//load the document from file 
var doc = XDocument.Load("..."); //== path to the file 

//write the xml to the screen 
Response.Write(doc.ToString()); 

如果你想使用XmlDocument相反,你會想使用Load而不是LoadXml

0
String text = File.ReadAllText(Server.MapPath("~/App_Data/sample.xml")); 
txtData.Text = text; 
相關問題