I know that there is a way to save data in an xml file with classes and their properties using XML Serialization.But Is there any way to save data without using classes and XML Serialization???
4 Answers
Absolutely - I would recommend LINQ to XML. For example:
XDocument doc = new XDocument(
new XElement("root",
new XElement("child1", "text"),
new XElement("child2",
new XElement("grandchild"))));
doc.Save("test.xml");
Obviously any of these literals can be supplied from your object data - and LINQ to XML makes it easy to create XML from sequences, LINQ queries etc.
Resulting test.xml file:
<?xml version="1.0" encoding="utf-8"?>
<root>
<child1>text</child1>
<child2>
<grandchild />
</child2>
</root>
LINQ to XML is a lovely API - much nicer than the old XmlDocument one, IMO.
2 Comments
XAttribute to create XML attributes, and where I've shown (say) "text" to specify the element text content, you can make that just use a variable. You should really learn LINQ to XML from scratch by reading the pages coming off the link in my answer. That's going to be much more effective than us just giving you specific examples.Absolutely, You can leverage Linq to Xml to create xml and then persist it to disk. Check out this Getting Started guide. Specifically, take a look the "Creating XML Trees" and "Serializing XML Trees" sections.
Comments
Save And Load Data with XmlDocument Class or use Linq to XML
Comments
There are quite a few different ways to accomplish this.
- Construct an XMLDocument and write code to create the document.
- Use LINQ to XML.
- Use a class derived from XmlWriter and write code to create the document.
- Use a manually created DataSet and write code to populate it.
- Use a strongly-typed DataSet created with the designer in Visual Studio and write code to populate it.
Depending on your needs you might also consider using the DataSet directly in lieu of classes.