In this article, i'll show you how to create and update an XML file in C#. Hope this help!
Example.xml
Example.xml
Create an XML file
Let's start by creating a new XML file. To do this, we'll use XmlTextWriter. Open your Main function and copy the code below:
static void Main(string[] args) {
// create a new file
string path = "E:\\Example.xml";
XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
// set output's view format
writer.Formatting = Formatting.Indented;
// write XML declaration
writer.WriteStartDocument(true);
// compose XML content
writer.WriteStartElement("inventory");
writer.WriteAttributeString("category", "vehicle");
writer.WriteStartElement("item");
writer.WriteAttributeString("id","p1");
writer.WriteString("Car");
writer.WriteEndElement();
writer.WriteStartElement("item");
writer.WriteAttributeString("id", "p2");
writer.WriteString("Bicycle");
writer.WriteEndElement();
writer.WriteEndElement();
// close session
writer.Close();
}
ResultExample.xml
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<inventory category="vehicle">
<item id="p1">Car</item>
<item id="p2">Bicycle</item>
</inventory>
Update an XML file
Now that we have created a simple XML file using XmlTextWriter. Next, let's modify it by XDocument. See the code below:
static void Main(string[] args){
string path = "E:\\Example.xml";
try {
XDocument doc = XDocument.Load(path);
XElement res = doc.Element("inventory");
// remove last item
res.LastNode.Remove();
// new item
XElement item = new XElement("item", "Motobike");
XAttribute att = new XAttribute("id", "p3");
item.Add(att);
// add to inventory
res.Add(item);
// save file
doc.Save(path);
}
catch (Exception e){
throw e; // file not found
}
}
ResultExample.xml
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<inventory category="vehicle">
<item id="p1">Car</item>
<item id="p3">Motobike</item>
</inventory>
No comments :
Post a Comment