XML Serialization - c#

I want to add multiple record one by one using XML serialization. I have three text boxes and a button which is used to get the data from the user and then serializae in XML file. However, when I add one record on it's own it's fine, but for the another record it declares multiple root elements which I am not able to handle.
I am doing XML serialization and I am getting this error in XML File
**<?xml version="1.0" encoding="utf-8"?>
<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">**
<CustomerId>3a8bb49e-f616-49a5-8ec8-1886881c3042</CustomerId>
<FirstName>HASEEB</FirstName>
<LastName>KHAN</LastName>
<CustomerEmail>SDCFDS</CustomerEmail>
**</sroot><?xml version="1.0" encoding="utf-8"?>
<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">**
<CustomerId>6d2cbe5e-e1fb-4526-9f98-bf396b4ded55</CustomerId>
<FirstName>ammae</FirstName>
<LastName>wdfjk</LastName>
<CustomerEmail>sdkcbnk</CustomerEmail>
</sroot>
As you can see in above XML code that there are multiple root element is written and I am not able to fix that I have a class called customer.cs and the code is written in this class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSearlizeProject.Classes
{
[Serializable]
[XmlRoot(ElementName = "sroot", Namespace = "urn:my-examples:shaping")]
public class Customer
{
string id = default(string);
string firstName = default(string);
string lastName = default(string);
string email = default(string);
public Customer()
{
}
public Customer(string id, string firstName, string lastName, string email)
{
CustomerId = id;
FirstName = firstName;
LastName = lastName;
Email = email;
}
[XmlElement("CustomerId")]
public string CustomerId
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
[XmlElement("FirstName")]
public string FirstName
{
get
{
return this.firstName;
}
set
{
this.firstName = value;
}
}
[XmlElement("LastName")]
public string LastName
{
get
{
return this.lastName;
}
set
{
this.lastName = value;
}
}
[XmlElement("CustomerEmail")]
public string Email
{
get
{
return this.email;
}
set
{
this.email = value;
}
}
}
}
And my C# code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
namespace XmlSearlizeProject.WebPages
{
public partial class CustomerPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void GeneralFunction(Stream xmlStream)
{
//xmlStream.Close();
string customerId = Guid.NewGuid().ToString();
Classes.Customer customer = new Classes.Customer(customerId,this.FirstNameTextBox.Text,this.LastNameTextBox.Text,this.EmailTextBox.Text);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Classes.Customer));
XmlDocument document = new XmlDocument();
document.Load(xmlStream);
XmlElement id = document.CreateElement("Id");
id.InnerText = customerId;
document.DocumentElement.InsertAfter(id, document.DocumentElement.LastChild);
XmlElement firstName = document.CreateElement("rtgr");
firstName.InnerText = customer.FirstName;
document.DocumentElement.InsertAfter(firstName, document.DocumentElement.LastChild);
XmlElement lastName = document.CreateElement("rtgtr");
lastName.InnerText = customer.LastName;
document.DocumentElement.InsertAfter(lastName, document.DocumentElement.LastChild);
XmlElement email = document.CreateElement("grbfr");
email.InnerText = customer.Email;
document.DocumentElement.InsertAfter(email, document.DocumentElement.LastChild);
XmlTextWriter xmlTextWriter = new XmlTextWriter(xmlStream, Encoding.UTF8);
xmlSerializer.Serialize(xmlTextWriter, customer);
xmlStream.Close();
}
private void SerializeCustomer()
{
if (File.Exists(Server.MapPath("~/Customer.xml")))
{
Stream xmlWriterStream = new FileStream(Server.MapPath("~/Customer.xml"), FileMode.Open, FileAccess.ReadWrite);
GeneralFunction(xmlWriterStream);
xmlWriterStream.Close();
}
}
private void DeSerializeCustomer()
{
Stream xmlReaderStream = new FileStream(Server.MapPath("~/Customer.xml"), FileMode.Open, FileAccess.Read, FileShare.Read);
XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(Classes.Customer));
Classes.Customer customer = (Classes.Customer)xmlDeSerializer.Deserialize(xmlReaderStream);
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
//if (!File.Exists(Server.MapPath("~/Customer.xml")))
//{
SerializeCustomer();
//}
//else
//{
// DeSerializeCustomer();
//}
}
}
}

It looks like you're serializing one customer at a time, versus serializing a list/array/collection of customers to the XML file.
Serializing one works because you have 1 root element - Customer. However, when serializing many, you will need to serializing the collection of customers to the XML file.
So then you'll have (example purposes only):
<Customers>
<sroot/>
<sroot/>
</Customers>
A few articles to look at on this:
C# Serializing a Collection of Objects
http://wcode.net/2009/08/serialize-collection-of-object-in-c/
http://www.codeproject.com/KB/cs/objserial.aspx

Define a schema definition (xsd) in the format you want your xml to look like. Then you can use some external tools like xsd2code. This would Auto-generate your "Customer" class to the format of your xsd. (In case if you are doing in manually). Then your xml will match the way you define in your xsd. Give it a try, defining a xsd for your xml is always a better practice.

You could just inherit from list something like this...
[Serializable]
[XmlRoot(ElementName = "sroot", Namespace = "urn:my-examples:shaping")]
public class CustomerList : List<Customer>
{
}
[Serializable]
public class Customer
{
...
}
Example usage...
CustomerList customerList = new CustomerList
{
new Customer
{
FirstName = "John",
LastName = "Doe",
Email = "johndoe#foobar.com",
CustomerId = "123"
},
new Customer
{
FirstName = "Jane",
LastName = "Doe",
Email = "janedoe#foobar.com",
CustomerId = "456"
}
};
Then your method would serialize the list (instance of CustomerList)...
SerializeCustomerList(CustomerList customers)
{
// Do serialize CustomerList instance...
}
Then the resulting XML would look like...
<sroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:my-examples:shaping">
<Customer>
<CustomerId>123</CustomerId>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<CustomerEmail>johndoe#foobar.com</CustomerEmail>
</Customer>
<Customer>
<CustomerId>456</CustomerId>
<FirstName>Jane</FirstName>
<LastName>Doe</LastName>
<CustomerEmail>janedoe#foobar.com</CustomerEmail>
</Customer>
</sroot>
Hope it helps!

Related

How to change a value inside XML file using c# Visual Studio

I am trying to change values inside XML file. This is my XML "person.xml" file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Table>
<Person>
<Number>1</Number>
<Name>Mariano</Name>
<Last Name>Italiano</Last Name>
<Age>36</Age>
</Person>
<Person>
<Number>2</Number>
<Name>John</Name>
<Last Name>Smith</Last Name>
<Age>32</Age>
</Person>
<Person>
<Number>3</Number>
<Name>Bob</Name>
<Last Name>Leckie</Last Name>
<Age>50</Age>
</Person>
<Person>
<Number>4</Number>
<Name>Patrick</Name>
<Last Name>Collins</Last Name>
<Age>63</Age>
</Person>
</Table>
And i want my program to do some things:
Find a name written in textBox2->Text. Then if the name exists i want to change it to name written in textBox3->Text.
Remove (if found) whole Person if CheckBoxDelete is set to true
I know how to create such a XML file (found an example somewhere) but i can't find a solution how to find and remove if neccessary.
I am using Visual Studio 2015 if it matters.
Thank You.
You can use XDocument to replace the value and delete the person according to the Name.
Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string filename = "D:\\test.xml";
private void BtnRePlace_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(filename);
doc.Descendants("Person").Descendants("Name").Where(i => i.Value == txtReplaceFirstName.Text).FirstOrDefault().SetValue(txtReplaceLastName.Text);
doc.Save(filename);
}
private void btndelete_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(filename);
doc.Descendants("Person").Where(i => i.Element("Name").Value == txtReplaceFirstName.Text&& i.Element("LastName").Value == txtReplaceLastName.Text).FirstOrDefault().Remove();
doc.Save(filename);
}
}
Besides, your xml file have an error, the Last Name should be LastName without space.
You could map (i.e. deserialize) the data to POCO objects, manipulate the data and serialize again. Might be a bit overkill though. As others stated, using XDocument might be good enough.
Here is a minimal example:
public class Person
{
[XmlElement]
public int Number { get; set; }
[XmlElement]
public string Name { get; set; }
[XmlElement]
public string LastName { get; set; }
[XmlElement]
public int Age { get; set; }
public override string ToString() => $"{Name} {LastName} is {Age}";
}
[XmlRoot("Table")]
public class RootObject
{
[XmlElement("Person")]
public List<Person> Persons;
}
class Program
{
static void Main(string[] args)
{
var xmlSer = new XmlSerializer(typeof(RootObject));
using var fs = new FileStream("input.xml", FileMode.Open);
var doc = (RootObject)xmlSer.Deserialize(fs);
foreach (var p in doc.Persons)
{
System.Console.WriteLine(p);
}
// do whatever with the RootObject instance
}
}
XML is the object, so consider re-using existing objects before creating more POCOs.
Here's code that shows how to find, delete, and update elements in XML. Take some time to learn XPath, it's very powerful, flexible, and available across nearly every platform.
using System;
using System.Threading.Tasks;
using System.Xml;
namespace testconsole
{
class Program
{
public static string strFileName = "c:\\temp\\test.xml";
static void Main(string[] args) {
XmlDocument xml = new XmlDocument();
xml.Load(strFileName);
string strMatchName = "Mariano";
string strXPath = "/Table/Person[Name='" + strMatchName + "']";
XmlElement ndPerson = (XmlElement)xml.SelectSingleNode(strXPath);
if (ndPerson != null) {
// Delete if the person is found
ndPerson.ParentNode.RemoveChild(ndPerson);
}
string strNewName = "Bob";
strXPath = "/Table/Person/Name[.='" + strNewName + "']";
XmlElement ndName = (XmlElement)xml.SelectSingleNode(strXPath);
if (ndName != null) {
ndName.InnerText = "Robert"; // new name
}
xml.Save(strFileName);
}
}
}

Trouble serializing and deserializing multiple objects

I currently playing with the XMLSerializerto understand how it works. I am able to serialize, save and de-serialize a single object without problem. However I run into problems when I try to de-serialize multiple objects. I get this error : Unhandled exception. System.InvalidOperationException: There is an error in XML document (10, 10).
---> System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no whitespace characters are allowed to appear before it.
I've tried this approach https://stackoverflow.com/a/16416636/8964654
here (and I could be doing it wrong)
public static ICollection<T> DeserializeList<T>()
{
string filePath = #"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
List<T> list = new List<T>();
using (FileStream fs = new FileStream (filePath, FileMode.Open)){
while(fs.Position!=fs.Length)
{
//deserialize each object in the file
var deserialized = (T)serializerTool.Deserialize(fs);
//add individual object to a list
list.Add(deserialized);
}
}
//return the list of objects
return list;
}
it didn't work
This is my original code. I intentionally call the SaveUser method twice to simulate the method being called twice at different times
[Serializable]
public class User: ISerializable{
public static void SaveUser(User user){
string filePath = #"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
using(FileStream fs = new FileStream(filePath, FileMode.Append)){
serializerTool.Serialize(fs, user);
}
}
public static void PrintUser(){
string filePath = #"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
using (FileStream fs = new FileStream (filePath, FileMode.Open)){
User u1 = (User)serializerTool.Deserialize(fs);
Console.WriteLine($"{u1.FirstName} {u1.LastName}, {u1.DOB.ToShortDateString()}");
}
}
}
class Program
{
static void Main(string[] args)
{
User user1 = new User(){
FirstName = "Kim",
LastName = "Styles",
Address = "500 Penn street, Dallas, 46589",
Username = "KimStyles#yahoo.com",
Password ="Kim2019",
DOB = (new DateTime(1990,10,01)),
Id = 2
};
User user2 = new User(){
FirstName = "Carlos",
LastName = "Santana",
Address = "500 Amigos street,San Jose, California, 46589",
Username = "Carlos.Santana#yahoo.com",
Password ="CarLosSan2019",
DOB = (new DateTime(1990,10,01)),
Id = 2
};
User.SaveUser(user1);
User.SaveUser(user2);
User.PrintUser();
}
}
below is how it saved XML data
<?xml version="1.0"?>
<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Kim</FirstName>
<LastName>Styles</LastName>
<DOBProxy>Monday, 01 October 1990</DOBProxy>
<Username>KimStyles#yahoo.com</Username>
<Password>Kim2019</Password>
<Address>500 Penn street, Dallas, 46589</Address>
<Id>1</Id>
</User>
<?xml version="1.0"?>
<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Carlos</FirstName>
<LastName>Santana</LastName>
<DOBProxy>Monday, 01 October 1990</DOBProxy>
<Username>Carlos.Santana#yahoo.com</Username>
<Password>CarLosSan2019</Password>
<Address>500 Amigos street,San Jose, California, 46589</Address>
<Id>2</Id>
</User>
I want to be able to retrieve all the data and print details of each individual user. How can I do this? Is there a better approach?
Your xml has multiple root elements, this is not allowed for valid xml.
If you change it to the format, this should work.
<?xml version="1.0"?>
<Users>
<user></user>
<user></user>
</Users>
I'd solve this problem as follow:
Create the User class
A Serializable class contains a user details.
[Serializable]
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public override string ToString()
{
return $"{ID}, {FirstName}, {LastName}, {DOB.ToShortDateString()}";
}
}
Create the Users class
Another Serializable class contains a list of User objects and handles both serialize and Deserialize routines:
[Serializable]
public class Users
{
public List<User> ThisUsers = new List<User>();
public void Save(string filePath)
{
XmlSerializer xs = new XmlSerializer(typeof(Users));
using (StreamWriter sr = new StreamWriter(filePath))
{
xs.Serialize(sr, this);
}
}
public static Users Load(string filePath)
{
Users users;
XmlSerializer xs = new XmlSerializer(typeof(Users));
using (StreamReader sr = new StreamReader(filePath))
{
users = (Users)xs.Deserialize(sr);
}
return users;
}
}
This way, you guarantee the XML file is formatted correctly, manage the users list (add, remove, edit).
Save (serialize) example
string filePath = #"TextFiles/Users.txt";
Users users = new Users();
for (int i = 1; i < 5; i++)
{
User u = new User
{
ID = i,
FirstName = $"User {i}",
LastName = $"Last Name {i}",
DOB = DateTime.Now.AddYears(-30 + i)
};
users.ThisUsers.Add(u);
}
users.Save(filePath);
Load (Deserialize) example:
string filePath = #"TextFiles/Users.txt";
Users users = Users.Load(filePath);
users.ThisUsers.ForEach(a => Console.WriteLine(a.ToString()));
//Or get a specific user by id:
Console.WriteLine(users.ThisUsers.Where(b => b.ID == 3).FirstOrDefault()?.ToString());
and here is how the generated XML file looks like
<?xml version="1.0" encoding="utf-8"?>
<Users xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ThisUsers>
<User>
<ID>1</ID>
<FirstName>User 1</FirstName>
<LastName>Last Name 1</LastName>
<DOB>1990-11-04T08:16:09.1099698+03:00</DOB>
</User>
<User>
<ID>2</ID>
<FirstName>User 2</FirstName>
<LastName>Last Name 2</LastName>
<DOB>1991-11-04T08:16:09.1109688+03:00</DOB>
</User>
<User>
<ID>3</ID>
<FirstName>User 3</FirstName>
<LastName>Last Name 3</LastName>
<DOB>1992-11-04T08:16:09.1109688+03:00</DOB>
</User>
<User>
<ID>4</ID>
<FirstName>User 4</FirstName>
<LastName>Last Name 4</LastName>
<DOB>1993-11-04T08:16:09.1109688+03:00</DOB>
</User>
</ThisUsers>
</Users>
Good luck.

Importing User Definitions from XML

I have been trying to make an export/import program but when I try to import the XML-information to the textbox it doesn't work.
C# snippet from program:
XmlDocument doc = new XmlDocument();
doc.Load(open.FileName);
foreach (XmlNode x in doc.DocumentElement)
textBox6.Text = x["Contact"].Value;
and the XML-file is as follows:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table1>
<Contact>example</Contact>
</Table1>
</NewDataSet>
Original image:
http://i.stack.imgur.com/0ks2F.png
try use InnerText instead of value
textBox6.Text = x["Contact"].InnerText;
A breakpoint on the line
textBox6.Text = x["Contact"].Value;
should be revealing...
That's just based on visual inspection - people who supply XML as png files don't get it examined by me lol...
You can use XmlSerializer to achieve same operation.
Checkout following code.
using System.Xml.Serialization;
using System.IO;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
NewDataSet objNewDataSet = new NewDataSet();
Table objTable = new Table();
objTable.Conact = "Hello";
objNewDataSet.Table1 = objTable;
StreamWriter objStream = new StreamWriter("C:\\Users\\Nirav Kamani\\Desktop\\abc.xml");
XmlSerializer objXmlSerializer = new XmlSerializer(typeof(NewDataSet));
objXmlSerializer.Serialize(objStream, objNewDataSet);
}
}
}
Model Classes.
using System.Xml.Serialization;
namespace DemoApplication
{
public class NewDataSet
{
[XmlElement]
public Table Table1 { get; set; }
}
}
namespace DemoApplication
{
public class Table
{
public string Conact { get; set; }
}
}
You can serialize and deserialize easily.
For more information check out following links.
I am just giving you a better approach to achieve same operation in terms of objects.
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Regarding XML serialization and customization

i am doing xml serialization but i need to customize the output.
my code is here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
namespace Serialize
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Movie movie = new Movie();
movie.Title = "Starship Troopers";
movie.ReleaseDate = DateTime.Parse("11/7/1997");
movie.Rating = 6.9f;
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Movie));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, movie);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
}
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}
}
public class Movie
{
string _Title = "";
DateTime _ReleaseDate;
float _Rating = 0;
[XmlElement("MovieName")]
public string Title
{
get
{
return _Title;
}
set
{
_Title = value;
}
}
[XmlElement("MovieRating")]
public float Rating
{
get
{
return _Rating;
}
set
{
_Rating = value;
}
}
[XmlElement("MovieReleaseDate")]
public DateTime ReleaseDate
{
get
{
return _ReleaseDate;
}
set
{
_ReleaseDate = value;
}
}
}
}
when i run this code then i am getting the output like
<?xml version="1.0" encoding="utf-8"?>
<Movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MovieName>Starship Troopers</MovieName>
<MovieRating>6.9</MovieRating>
<MovieReleaseDate>1997-11-07T00:00:00</MovieReleaseDate>
</Movie>
here if u see then u will note few extra info is coming which i don't require
that xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
this info is coming along with Movie tag. so please what i need to change in my code as a result the extra info will not show in the code.
so my code will look like
<?xml version="1.0" encoding="utf-8"?>
<Movie>
<MovieName>Starship Troopers</MovieName>
<MovieRating>6.9</MovieRating>
<MovieReleaseDate>1997-11-07T00:00:00</MovieReleaseDate>
</Movie>
please help with rectification in detail.
I think you'll have to remove them manually, like here:
How to remove all namespaces from XML with C#?

Reading and writing an existing xml file c# 3.0 / .net3.5

I have a xml-file which I want to read. How can I do it? I would not load whole xml file at runtime
(XmlDocument _xd = XmlDocument.Load(path))
I want to do it with Readers, but I can not achieve with it.
At the same time I want to add nodes to this xml-file with writers. How do these work with XDocument or at c# 3.5.
Kind Regards.
I think this is useful.
Here's an example:
using System;
using System.Xml;
namespace ReadXml1
{
class Class1
{
static void Main(string[] args)
{
// Create an isntance of XmlTextReader and call Read method to read the file
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read())
{
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
// Read this element's properties and display them on console
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" + textReader.LocalName);
Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
Console.WriteLine("Depth:" + textReader.Depth.ToString());
Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
}
}
}
}
And here's an example for XMLWriters:
using System.Xml;
class Program
{
class Employee
{
int _id;
string _firstName;
string _lastName;
int _salary;
public Employee(int id, string firstName, string lastName, int salary)
{
this._id = id;
this._firstName = firstName;
this._lastName = lastName;
this._salary = salary;
}
public int Id { get { return _id; } }
public string FirstName { get { return _firstName; } }
public string LastName { get { return _lastName; } }
public int Salary { get { return _salary; } }
}
static void Main()
{
Employee[] employees = new Employee[4];
employees[0] = new Employee(1, "David", "Smith", 10000);
employees[1] = new Employee(3, "Mark", "Drinkwater", 30000);
employees[2] = new Employee(4, "Norah", "Miller", 20000);
employees[3] = new Employee(12, "Cecil", "Walker", 120000);
using (XmlWriter writer = XmlWriter.Create("employees.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
foreach (Employee employee in employees)
{
writer.WriteStartElement("Employee");
writer.WriteElementString("ID", employee.Id.ToString());
writer.WriteElementString("FirstName", employee.FirstName);
writer.WriteElementString("LastName", employee.LastName);
writer.WriteElementString("Salary", employee.Salary.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
Here is an example of loading xml file with XDocument, adding a child node and saving it to the use :
// Load XML file :
XDocument xdoc = XDocument.Load(path);
// Parse XML :
//XDocument xdoc = XDocument.Parse("<YourRootElement><ChildElement>Child 1</ChildElement></YourRootElement>");
// Add Child Node to loaded xml :
xdoc.Element("YourRootElement").Add(
new XElement("ChildElement", "Child 2"));
// Save XML to file :
xdoc.Save(path);
EDIT : Use XDocument.Parse method to load XML from memory.
Didn't you consider also using LINQ? Like this (just pseudo-like, you would have to look it up on the web, but just to have an idea).
XDocument xmlDoc = //load or parse with XDocument.Load(..) or XDocument.Parse(...)
List<MyObject> myObj = (from myObject in xmlDoc.Descendants("myObjectTag")
select new MyObject
{
Name = (string)myObject.Attribute("name"),
...
}
).toList<MyObject>();
VoilĂ , here's a blog post I just found by quickly googling: * click *

Categories