2011-02-08 159 views
74
protected void Page_Load(object sender, EventArgs e) 
{ 
    XmlDocument doc = new XmlDocument(); 
    try 
    { 
     string path = Server.MapPath("."); 
     doc.Load(path+"whatever.xml"); 
    } 
    catch (Exception ex) 
    { 
     lblError.Text = ex.ToString(); 
     return; 
    } 

    // Convert XML to a JSON string 
    string JSON = XmlToJSON(doc); 

    // Replace \ with \\ because string is being decoded twice 
    JSON = JSON.Replace(@"\", @"\\"); 

    // Insert code to process JSON at end of page 
    ClientScriptManager cs = Page.ClientScript; 
    cs.RegisterStartupScript(GetType(), "SpaceJSON", "space_processJSON('" + JSON + "');", true); 
} 

相反,如果從文件中加載xml,如何從字符串加載它?XmlDocument - 從字符串加載?

+3

查找[`XmlDocument`類](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx)。你會很快找出你自己。 – 2011-02-08 04:49:03

+0

`LoadXml()` - http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx – 2014-06-06 14:57:14

回答

175
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(str); 

其中str是您的XML字符串。有關更多信息,請參閱MSDN article