C # create a simple XML file

How to create a simple xml file and save it on my system?

+49
c # xml
Nov 04 2018-10-10T00:
source share
2 answers

You can use XDocument :

new XDocument( new XElement("root", new XElement("someNode", "someValue") ) ) .Save("foo.xml"); 

If the file you want to create is very large and cannot fit into memory, you can use XmlWriter .

+78
Nov 04 '10 at 8:37
source share

Two ways: you can use XMLwriter, or you can use serialization.

I would recommend serialization, but if it's simple, use an XmlDocument, for example:

 using System; using System.Xml; public class GenerateXml { private static void Main() { XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode productsNode = doc.CreateElement("products"); doc.AppendChild(productsNode); XmlNode productNode = doc.CreateElement("product"); XmlAttribute productAttribute = doc.CreateAttribute("id"); productAttribute.Value = "01"; productNode.Attributes.Append(productAttribute); productsNode.AppendChild(productNode); XmlNode nameNode = doc.CreateElement("Name"); nameNode.AppendChild(doc.CreateTextNode("Java")); productNode.AppendChild(nameNode); XmlNode priceNode = doc.CreateElement("Price"); priceNode.AppendChild(doc.CreateTextNode("Free")); productNode.AppendChild(priceNode); // Create and add another product node. productNode = doc.CreateElement("product"); productAttribute = doc.CreateAttribute("id"); productAttribute.Value = "02"; productNode.Attributes.Append(productAttribute); productsNode.AppendChild(productNode); nameNode = doc.CreateElement("Name"); nameNode.AppendChild(doc.CreateTextNode("C#")); productNode.AppendChild(nameNode); priceNode = doc.CreateElement("Price"); priceNode.AppendChild(doc.CreateTextNode("Free")); productNode.AppendChild(priceNode); doc.Save(Console.Out); } } 
+30
Nov 04 '10 at 8:40
source share



All Articles