gpt4 book ai didi

asp.net - 在 asp.net 中编写和下载 xml 文件的最佳方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 02:37:51 25 4
gpt4 key购买 nike

我有一个 Web 表单,它需要将用户输入的数据保存到一个文件中,并在客户端电脑上保存,该表单还可以从保存的文件中读取并在以后重新填充字段。没有文件会保存到服务器端,所以我希望在编写时需要涉及流式传输。

我认为 XML 是实现此目的的一种简单方法,但我在方法上受阻。 XML文件? XML 编写器?我什至无法找到我想要的正确搜索词。

在此先感谢您的指点。

最佳答案

您需要使用 XML 序列化。看看这篇 [MSDN 文章][1]。以下是关于序列化和反序列化的摘录:

How to Serialize an Object

To Serialize and object, we need fewinstances of the in-built classes. Solets first create an instance of aXmlDocument class from System.Xmlnamespace. Then create an instance ofXmlSerializer class fromSystem.Xml.Serialization namespacewith parameter as the object type. Nowjust create an instance of theMemoryStream class from System.IOnamespace that is going to help us tohold the serialized data. So all yourinstances are there, now you need tocall their methods and get yourserialzed object in the xml format. Myfunction to Serialize an object lookslike following.

private string SerializeAnObject(object obj)

{

System.Xml.XmlDocument doc = new XmlDocument();

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

System.IO.MemoryStream stream = new System.IO.MemoryStream();

try

{

serializer.Serialize(stream, obj);

stream.Position = 0;

doc.Load(stream);

return doc.InnerXml;

}

catch

{

throw;

}

finally

{

stream.Close();

stream.Dispose();

}

}

How to DeSerialize an Object

To DeSerialize an object you need aninstance of StringReader, XmlReaderand XmlSerializer class in order toread the xml data (Serialized data),read it into XmlReader and DeSerializeit respectively. So in brief myfunction to DeSerialize the objectlooks like following.

private object DeSerializeAnObject(string xmlOfAnObject)

{

MyClass myObject = new MyClass();

System.IO.StringReader read = new StringReader(xmlOfAnObject);

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType());

System.Xml.XmlReader reader = new XmlTextReader(read);

try

{

myObject = (MyClass)serializer.Deserialize(reader);

return myObject;

}

catch

{

throw;

}

finally

{

reader.Close();

read.Close();

read.Dispose();

}

}


[1]: https://msdn.microsoft.com/en-us/library/182eeyhh%28v=VS.90%29.aspx

关于asp.net - 在 asp.net 中编写和下载 xml 文件的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3523366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com