"Larry Williams" <Larry
Wi******@discussions.microsoft.com> wrote in message
news:AC**********************************@microsof t.com...
Is there an easy way to convert a string of data to XML format without having
to create the xml one field at a time?
Certainly, but the easier the approach you take, the less meaningful structure your
XML document is likely to have.
First, suppose you have the string of data (strData), "03040517761492oceanblue".
This string can easily turned into an XML document,
XmlDocument doc = new XmlDocument( );
doc.LoadXml( string.Format( "<pwd>{0}</pwd>", strData));
Nothing difficult about that, but nothing "smart" about it either. The one-step
process yields you with a one-element XML document using only .NET's
standard string formatting (moreso than any System.Xml functionality.)
For the next example assume your data is comma-delimited, such as,
string strData = "mary,kate,ashley,olson";
This time you can use the Replace( ) function to inject closing and opening tags at
the positions within the string where there are commas now, and then wrap them
in an initial opening and a concluding closing tag.
XmlDocument doc = new XmlDocument( );
doc.LoadXml( string.Format( "<list><name>{0}</name></list>", strData.Replace( ",", "</name><name>")));
This leads to the XML instance document (when printed with indented formatting),
<list>
<name>mary</name>
<name>kate</name>
<name>ashley</name>
<name>olson</name>
</list>
However, what you'll find with these approaches is that the more structure you want
to impose, the greater the need is for you to operate on a field-by-field basis. For
instance, you can't escape at least examining each individual string token in the above
example were your XML document required to hold sufficient information to distinguish
between the Olson Twins' given and last names,
string[] names = strData.Split( new char[] { ',' });
System.Text.StringBuilder buf = new System.Text.StringBuilder( );
buf.Append( "<list>");
foreach( string name in names)
buf.AppendFormat( "<{0}>{1}</{0}>", ( ( 5 == name.Length ) ? "lastName" : "firstName" ), name);
buf.Append( "</list>");
XmlDocument doc = new XmlDocument( );
doc.LoadXml( buf.ToString( ));
This converts the string of comma-delimited data into the following XML document,
<list>
<firstName>mary</firstName>
<firstName>kate</firstName>
<firstName>ashley</firstName>
<lastName>olson</lastName>
</list>
Before we start arguing over whether Mary Kate is one first name or two; :-) the
amount of effort necessary is application-dependent. There's no silver bullet that
brings into existence an ordered structure out of thin air -- one that turns data into
information.
Derek Harmon