views:

357

answers:

6

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>
+1  A: 

Assuming you're using .NET:

  1. XmlWriter
  2. XmlArrayAttribute, XmlArrayItem
Dave Swersky
A: 

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?

Dabblernl
i'm using .net 2.0
raklos
Thats a shame, Linq to XML is worth the upgrade to 3.5 all by by itself IMO
Tim Jarvis
A: 

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.

Brian Agnew
+1  A: 

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));
Tim Jarvis
A: 

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());
 }

}
Ganesh R.
A: 

Use Gelatin with this syntax:

define nl /[\r\n]/
define ws /\s+/
define fieldname /\w+/
define value /[^\r\n,]/

grammar input:
    match nl:
        do.skip()
    match fieldname ':' ws value nl:
        out.add('$0', '$3')
knipknap