开发者

What is the easiest way of handling xml files with C#?

I'm developing a windows app using C#. I chose xml for data storage.

It is required to read xml file, make small changes, and开发者_C百科 then write it back to hard disk.

Now, what is the easiest way of doing this?


XLinq is much comfortable than the ordinary Xml, because is much more object oriented, supports linq, has lots of implicit casts and serializes to the standard ISO format.


The best way is to use XML Serialization where it loads the XML into a class (with various classes representing all the elements/attributes). You can then change the values in code and then serialize back to XML.

To create the classes, the best thing to do is to use xsd.exe which will generate the c# classes for you from an existing XML document.


I think the easiest way of doing it - it is using XmlDocument class:

var doc = new XmlDocument();
doc.Load("filename or stream or streamwriter or XmlReader");
//do something
doc.Save("filename or stream or streamwriter or XmlWriter");


I think I found the easiest way, check out this Project in Codeproject. It is easy to use as XML elements are accessed similarly to array elements using name strings as indexes.

Code sample to write bool property to XML:

Xmlconfig xcfg = new Xmlconfig("config.xml", true);
xcfg.Settings[this.Name]["AddDateStamp"]["bool"].boolValue = checkBoxAddStamp.Checked;
xcfg.Save("config.xml");

Sample to read the property:

Xmlconfig xcfg = new Xmlconfig("config.xml", true);
checkBoxAddStamp.Checked = xcfg.Settings[this.Name]["AddDateStamp"]["bool"].boolValue;

To write string use .Value, for int .intValue.


You can use LINQ to read XML Files as described here...

LINQ to read XML


Check out linq to XML

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜