Best way to get a comma delineated string into xml format?
Question
Using VB.net (.net 2.0) I have a string in this format:
record1_field1,record1_field2,record2_field3,record2_field1,record2_field2,
etc...
I wonder what the best (easiest) way is to get this into an xml?
I can think of 2 ways:
Method 1: - use split to get the items in an array - loop through array and build an xml string using concatenation
Method 2: - use split to get the items in an array - loops through array to build a datatable - use writexml to output xml from the datatable
The first sounds pretty simple but would require more logic to build the string.
The second seems slicker and easier to understand.
Are there other ways to do this?
Solution
I would do something like this:
XmlDocument doc = new XmlDocuent();
string[] data = csv.split(',');
XmlNode = doc.CreateElement("root");
foreach(string str in data)
{
XmlNode node = doc.CreateElement("data");
node.innerText = str;
root.AppendChild(node);
}
Console.WriteLine(doc.InnerXML);
Should return something like this:
<root>
<data>field 1</data>
<data>field 2</data>
<data>field 3</data>
</root>
You would have to nest loops / tokenize a bit differently for nested data...
OTHER TIPS
Instead of doing string concatenation, you could probably create an XmlDocument and stuff it with the appropriate XmlElement and XmlAttribute objects from your string... Then, write out the XmlDocument object...