given a bunch of data in the form of name-value pairs how can i construct that into xml?
eg:
Title : Mr
Name : John
Surname : Doe
as valid xml sililar to:
<Data>
<Title>Mr</Title>
<Name >John</Name >
<Surname >Doe</Surname >
</Data>
given a bunch of data in the form of name-value pairs how can i construct that into xml?
eg:
Title : Mr
Name : John
Surname : Doe
as valid xml sililar to:
<Data>
<Title>Mr</Title>
<Name >John</Name >
<Surname >Doe</Surname >
</Data>
You can do that using XElement in System.Linq.Xml
var data=nameValuePair.Value;
var xelement=new XElement("Data",
new XElement("Title",data.Title),
new XElement("Name",data.Name),
new XElement("Surname",data.Surname));
Does this answer you question?
Whatever you do, use an XML-aware API to do it. Don't simply read the string and write out between tags. It's tempting since it's convenient, but you have to worry about character and entity encoding to generate XML properly.
Assuming you have a dictionary with the key value pairs..something like..
XElement xe = new XElement("Data", from kvp in dict
select new XElement(kvp.Key, kvp.Value));
If the all the data is always in the said form & you have a bunch of it, Create a class with members & serialize it to xml.
public class test
{
public string title;
public string name;
public string surname;
}
void main()
{
List<test> t = new List<test>();
test t1 = new test();
t1.title = "Mr.";
t1.name = "John";
t1.surname = "Doe";
.
.
.
test tn = new test();
t.Add(t1);
t.Add(t2);
.
.
.
.
t.Add(tn);
//Serialize to xml.
try
{
using (FileStream fs = new FileStream(szFileName, FileMode.Create))
{
XmlSerializer xs = new XmlSerializer(typeof(List<test>));
xs.Serialize(fs, t);
}
}
catch(Exception Ex)
{
Messagebox.Show(Ex.ToString());
}
//And deserialize the data from xml to objects
try
{
using (System.IO.FileStream fs = new FileStream(szDataFile,FileMode.Open))
{
System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(typeof(List<test>));
List<test> t1 = new List<test>();
t1 = xs.Deserialize(fs) as List<test>;
}
}
catch(Exception Ex)
{
Messagebox.Show(Ex.ToString());
}
}