Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a string array:
mainstring = peter|100|john|200|sue|300

and want to convert it into an xml string that looks like-
XML
<xml>
<identity>
<id><name>peter</name><salary>100</salary></id>
<id><name>john</name><salary>200</salary></id>
<id><name>sue</name><salary>300</salary></id>
</identity>
</xml>

Note: the mainstring can have more names and salary values in array, so the code has to be dynamic

Any help is greatly appreciated!!!!
Posted
Updated 19-May-11 17:47pm
v2
Comments
Sandeep Mewara 19-May-11 23:49pm    
You need to split it and then create the XML... did you try anything?

Try this

C#
mainstring = "peter|100|john|200|sue|300";
string[] data = mainstring.Split('|'); // Split data

XElement identity = new XElement("identity"));

// Walk array of data
for (int count = 0; count < data.Length; count += 2)
{
  XElement elm = new XElement("id",
    new XElement("name", data[count]),
    new XElement("salary", data[count + 1]));

  identity.Add(elm);
}

XElement xml = new XElement("xml", identity);


Output of "xml" variable XElement:

XML
<xml>
<identity>
<id><name>peter</name><salary>100</salary></id>
<id><name>john</name><salary>200</salary></id>
<id><name>sue</name><salary>300</salary></id>
</identity>
</xml>


I have not compiled it or any test. Just right out of memory.
Good luck!
 
Share this answer
 
Comments
hemantwithu 20-May-11 2:33am    
No not like that but i tried in this way
Kim Togo 21-May-11 7:27am    
Do you mean that "mainstring" is an array of strings?
Hi i got the solution please tel me whether this is correct or not.

C#
string[] names = { "KRISH", "JOHN" };

      using (XmlWriter writer = XmlWriter.Create(@"D:\sample.xml"))
      {
        writer.WriteStartDocument();
        writer.WriteStartElement("Names");

        foreach (string name in names)
        {
          writer.WriteStartElement("Name");
          writer.WriteElementString("FirstName", name.ToString());
          writer.WriteEndElement();
        }

        writer.WriteEndElement();
        writer.WriteEndDocument();
      }
 
Share this answer
 
Comments
hemantwithu 20-May-11 0:17am    
Is this code is Correct ?Am getting the output same

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900