Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing xml and reading it back c#

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

like image 250
Data Avatar asked Jun 10 '17 20:06

Data


People also ask

How do I read XML file as text?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).

How read and write data from XML in C#?

The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively.


1 Answers

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

like image 96
Alan Wolman Avatar answered Oct 06 '22 00:10

Alan Wolman