开发者

Work with xml in c#

I want to do something like this in my program with c# code: if a xml file does not exists create it and insert an object of a class in it, else if it has created already but the creation time is just today add my object at the end of it, else clear current xml file and insert the ob开发者_如何学Pythonject in it.

how can i do that?

Note:i almost did it by "xmlSerializer", but i couldnt add data at the end of my xml file.


Try using the LINQ to XML class XElement. It is quite handy. You may still need to use the XmlSerializer in order to turn your object to XML. When using the XMLSerializer make sure you use a static one as the constructor for XmlSerializer is very heavy.

Start off by adding A reference to System.Xml.Linq. You can use XElement.Load to read the existing xml from a file. You can use .Parse to read the xml string from your serialized object. You can use the add method to add your xml to the endof the xml you read. And .Save to write it out to a file. Here is the msdn referenece for XElement http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx

StringWriter sw = new StringWriter();
XmlSerializer ser = new XmlSerializer(typeof(Nothing));
ser.Serialize(sw, new Nothing(){AStringInNothing = "asd"});
sw.ToString();
var whatYouWant = XElement.Parse(sw.ToString());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜