In this tutorial we’re going to find how to read and write xml files in c#.
XML files can be used to store data, they replace the old ini files.
XML have a structure like this one:
|
|
These file are made of nodes, each node can contain more nodes inside, and each of them may have attributes.
In the example before, root
, node
, item1
and item2
are nodes, only the node item1
has an attribute set to “abc123” as value.
The node item2
is an empty node.
Before start add this on top of your code:
|
|
To write an xml file you do:
|
|
This code will create a file with the same content you saw before.
new XElement(name)
create a new element, if you don’t put other arguments other than the name, it will create an empty element(like the item2).
As arguments you can put the content of the element(just write a string) or you can create a new element to make nested nodes.
new XAttribute(propriety, value)
let you create an attribute to the element.
doc.Save(file name)
This function just save the file.
As you see it’s very easy to create a xml file, to read it it’s even easier.
To read data from xml file you do:
|
|
I hope you found this quick tutorial useful 😄
As always, let me know on Twitter if you liked it! @CodeSailer