...is a blog containing code (and sometimes other things) that make geeks go, WTF??
Today's horror just looks like a random jumble of appending constants that probably didn't need to be constants. Until you look more closely, and you realise it's constructing XML. Except there's a bug: tags are being closed with a backslash - \ - rather than the correct slash - /.
Just in case anyone needs the hint:
private static string FormatData( SqlDataReader dr )
{
using ( StringWriter sw = new StringWriter() )
{
XmlTextWriter tw = new XmlTextWriter( sw );tw.Formatting = Formatting.Indented;
tw.WriteStartElement( "Items" );
while ( dr.Read() )
{
tw.WriteStartElement( "Item" );
tw.WriteAttributeString( "key", (string)dr[0] );
tw.WriteString( (string)dr[1] );
tw.WriteEndElement();
}tw.WriteEndElement();
return sw.ToString();
}
}
If you need to write XML, use an XmlTextWriter. The code is shorter and clearer, and is more likely to work, considering cases like escaping invalid characters. Also note that I got it to indent the XML for me. Running this on a reader containing the results of SELECT emp_id, lname FROM employee
on SQL Server's pubs
database, we get:
<Items>
<Item key="A-C71970F">Cruz</Item>
<Item key="AMD15433F">Devon</Item>
<Item key="A-R89858F">Roulet</Item>
<Item key="ARD36773F">Domingues</Item>
<Item key="CFH28514M">Hernadez</Item>
<Item key="CGS88322F">Schmitt</Item>
<Item key="DBT39435M">Tonini</Item>
<Item key="DWR65030M">Roel</Item>
<Item key="ENL44273F">Lincoln</Item>
<Item key="F-C16315M">Chang</Item>
<Item key="GHT50241M">Thomas</Item>
<Item key="HAN90777M">Nagy</Item>
<Item key="HAS54740M">Snyder</Item>
<Item key="H-B39728F">Bennett</Item>
<Item key="JYL26161F">Labrune</Item>
<Item key="KFJ64308F">Josephs</Item>
<Item key="KJJ92907F">Jablonski</Item>
<Item key="LAL21447M">Lebihan</Item>
<Item key="L-B31947F">Brown</Item>
<Item key="MAP77183M">Paolino</Item>
<Item key="MAS70474F">Smith</Item>
<Item key="MFS52347M">Sommer</Item>
<Item key="MGK44605M">Karttunen</Item>
<Item key="MJP25939M">Pontes</Item>
<Item key="M-L67958F">Larsson</Item>
<Item key="MMS49649F">Saveley</Item>
<Item key="M-P91209M">Pereira</Item>
<Item key="M-R38834F">Rance</Item>
<Item key="PCM98509F">McKenna</Item>
<Item key="PDI47470M">Ibsen</Item>
<Item key="PHF38899M">Franken</Item>
<Item key="PMA42628M">Accorti</Item>
<Item key="POK93028M">Koskitalo</Item>
<Item key="PSA89086M">Afonso</Item>
<Item key="PSP68661F">Parente</Item>
<Item key="PTC11962M">Cramer</Item>
<Item key="PXH22250M">Henriot</Item>
<Item key="RBM23061F">Muller</Item>
<Item key="R-M53550M">Mendel</Item>
<Item key="SKO22412M">Ottlieb</Item>
<Item key="TPO55093M">O'Rourke</Item>
<Item key="VPA30890F">Ashworth</Item>
<Item key="Y-L77953M">Latimer</Item>
</Items>
No comments:
Post a Comment