2012-11-02 49 views
4

我試圖將一些值存儲到一個xml文件中。我已經創建了一個Xml文件並嘗試覆蓋數據。該代碼被賦予..使用Asp-C寫入Xml文件#

/*storepassword.cs *// 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 

public class StorePassword 
{ 
    public StorePassword() 
    { 
    } 
    public void store(NewPassword nps) 
    { 
     XmlDocument XmlDoc = new XmlDocument(); 

     //XmlDoc.Load(@"Password.xml"); 
     XmlDoc.LoadXml("Password.xml"); 

     XmlNode root = XmlDoc.DocumentElement; 
     XmlNode myNode1 = root.SelectSingleNode("UserName"); 
     XmlNode myNode2 = root.SelectSingleNode("PassWord"); 
     myNode1.Value = "sjn"; 
     myNode2.Value = "sjn123"; 
     XmlDoc.Save(@"Password.xml"); 
    } 
} 

//NewPassword.cs 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

public class NewPassword 
{ 

    public NewPassword() 
    { 

    } 
    public string username{ get; set; } 
    public string Password{ get; set; } 
} 

上按一下按鈕..

NewPassword nps = new NewPassword(); 
nps.username = TxtUser.Text; 
nps.Password = TxtNewPassword.Text; 
StorePassword sp=new StorePassword(); 
sp.store(nps); 

現有的XML文件包含以下..

<?xml version="1.0" encoding="utf-8"?> 
<ROOT> 
    <UserName>abc</UserName> 
    <PassWord>123</PassWord> 
</ROOT> 

但它不工作..

根級別的數據無效。 1號線,位置1

此錯誤occures ..

Ichanged代碼爲XmlDoc.Load(@"Password.xml");

現在錯誤改爲

Root element is missing. 

    Description: An unhandled exception occurred during the execution of the current web     request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Xml.XmlException: Root element is missing. 

爲什麼出現這種情況?

+1

LoadXml用於加載一個XML文檔表示爲文本。你想使用加載代替(如在註釋行) –

+0

k ..讓我試試.. – Sudix

+0

根元件丟失 現在發生此錯誤 – Sudix

回答

0

當你加載你的Xml時,你需要使用Server.MapPath。 XmlDoc.LoadXml(Server.MapPath("Password.xml"));

1

嘗試使用XML序列化:

public static partial class ObjectXMLSerializer<T> where T : class 
{ 
      private static void SaveToDocumentFormat(T serializableObject, System.Type[] extraTypes, string path, IsolatedStorageFile isolatedStorageFolder) 
      { 
       using (TextWriter textWriter = CreateTextWriter(isolatedStorageFolder, path)) 
       { 
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes); 

        //Cuong: set name space to null 
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 
        ns.Add("", ""); 
        xmlSerializer.Serialize(textWriter, serializableObject, ns); 
       } 
      } 
      public static void Save(T serializableObject, string path) 
      { 
        SaveToDocumentFormat(serializableObject, null, path, null); 
      } 

} 
0

刪除

<?xml version="1.0" encoding="utf-8"?> 

<?xml version="1.0" encoding="utf-8"?> 
<ROOT> 
    <UserName>abc</UserName> 
    <PassWord>123</PassWord> 
</ROOT> 

我不知道爲什麼它的工作原理,但我們這樣做,在我們的代碼所有的時間。是的,你應該使用XmlDocument.Load不是XmlDocument.LoadXml