Reputation: 113
ok, I am now using the document method for writing my XML instead of the XmlWriter. I have written my XML file with.
userNode = xmlDoc.CreateElement("user");
attribute = xmlDoc.CreateAttribute("age");
attribute.Value = "39";
userNode.Attributes.Append(attribute);
userNode.InnerText = "Jane Doe";
rootNode.AppendChild(userNode);
But the question is again how to read these settings back.
<users>
<user name="John Doe" age="42" />
<user name="Jane Doe" age="39" />
</users>
The format of the file I can figure out how to read the age variable but can't get my hands on the name property. my XML file is slightly different to above but not by much
Upvotes: 5
Views: 6629
Reputation: 683
Writing XML files element by element can be quite time consuming - and susceptible to errors.
I would suggest using an XML Serializer for this type of job.
If you are not concerned with the format - and the requirement is just to be able to serialize to XML and deserialize at a later time the code can be as simple as follows:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
string filepath = @"c:\temp\users.xml";
var usersToStore = new List<User>
{
new User { Name = "John Doe", Age = 42 },
new User { Name = "Jane Doe", Age = 29 }
};
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
{
XmlSerializer serializer = new XmlSerializer(usersToStore.GetType());
serializer.Serialize(fs, usersToStore);
}
var retrievedUsers = new List<User>();
using (FileStream fs2 = new FileStream(filepath, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(usersToStore.GetType());
retrievedUsers = serializer.Deserialize(fs2) as List<User>;
}
Microsoft provides some good examples in the .Net documentation - Introducing XML Serialization
Upvotes: 5
Reputation: 6217
Use XDocument class instead of XmlDocument, if you can. It is much easier to work with. To write and then read your XML, you can do this:
var fileName = @"foo.xml";
// Write XML
var xdoc = new XDocument(
new XElement("users",
new XElement("user",
new XAttribute("name", "John Doe"),
new XAttribute("age", "42")),
new XElement("user",
new XAttribute("name", "Jane Doe"),
new XAttribute("age", "39"))));
xdoc.Save(fileName);
// Read XML
var xdoc2 = XDocument.Load(fileName);
foreach (var userxml in xdoc2.Root.Elements("user"))
{
var name = userxml.Attribute("name");
var age = userxml.Attribute("age");
// use values as needed ...
}
Upvotes: 0
Reputation: 168
Try using System.Xml
(it's more clear to use):
For Saving:
XmlDocument xdoc = new XmlDocument();
...
xdoc.Save("test.xml");
For Reading:
XmlDocument xdoc = new XmlDocument();
...
xdoc.Load("test.xml");
Upvotes: 0