Writing to an Xml File Using Asp-C #

I am trying to save some values ​​in an xml file. I have already created an Xml file and am trying to overwrite the data. Code is provided ..

/*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; } } 

at the touch of a button.

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

An existing Xml file contains the following.

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

But it does not work.

Data at the root level is invalid. Line 1, Position 1

this error occurs.

Changed the code as XmlDoc.Load(@"Password.xml");

now the error has changed to

 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. 

Why is this happening?

+4
source share
3 answers

Try using XML serialization:

 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); } } 
+1
source

When loading Xml, you need to use Server.MapPath. XmlDoc.LoadXml(Server.MapPath("Password.xml"));

0
source

remove

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

from

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

I don't know why this works, but we do it all the time in our code. And yes, you should use XmlDocument.Load not XmlDocument.LoadXml

0
source

Source: https://habr.com/ru/post/1443616/


All Articles