Convert Hashtable

  • Thread starter Thread starter Joe
  • Start date Start date
J

Joe

Hi,

I have a Hashtable of string objects that I need to convert to a XML string.
Any ideas how to do this?

Thanks
 
It depends on the schema of the output XML.
You could use one of the approach.
- Use StringBuilder
- Use XmlWriter
- Use XmlDocument

Could you describe the desired output XML schema?

Thi
http://thith.blogspot.com
 
Thanks for the response. The desired output is just the key as the element
with the value. Is StringBuilder the best approach?
 
Hi,

The StringBuilder is simple and best approach to your requirements.
I guess the desired output is like this:
<key>value</key>
If so, make sure the key is a valid XML identifier.
The safer way is <item key="key">value</item>.
Sample code:
const string pattern = "<item key=\"{0}\">{1}</item>";
StringBuilder buffer = new StringBuilder("<table>");
foreach (DictionaryEntry entry in theHashTable)
{
buffer.AppendFormat(pattern, entry.Key, entry.Value);
}
buffer.Append("</table>");
return buffer.ToString();

Hope it helps,
Thi
http://thith.blogspot.com
 
IMO, using StringBuilder directly is a fairly sure way of introducing
an occasional bug... all you need is a reserved xml character in either
the key or value, and it's broken. That's way too brittle for my
liking.

You can, however, do something like below; fairly hard to break this
via content... also, note that the order of items is not guaranteed by
Hashtable

Marc

Hashtable ht = new Hashtable();
ht.Add("Test", "Something");
ht.Add("Whatever", "abcf");
ht.Add("asd", "adsfgaa");

StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
writer.WriteStartElement("items");
foreach (DictionaryEntry item in ht)
{
writer.WriteStartElement("item");
writer.WriteAttributeString("key",
item.Key.ToString());
writer.WriteValue(item.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
}
Console.WriteLine(sb.ToString());
 
Yes, that is safer. XmlWriter should know how to escape illegal
characters.
 
Thanks for the posts. That makes sense to use XMLWriter and I appreciate
the help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top