Sean
Sean

Reputation: 163

Write unencoded File file using C#

The following code needs to produce an XML file.

string path = @"c:\load\myFile.xml";
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpFloors"].ConnectionString);
        SqlCommand cmd;
        cmd = new SqlCommand("select coords.xyid as '@id', xmin, xmax, ymin, ymax,(select brief, long, img from floordesc where coords.xyid = floordesc.xyid for xml path(''),Type) as 'desc' from coords where xyid <> '' for xml path('coord'), Elements XSINIL,root('coords')", connection);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet("coords");
        da.Fill(ds, "coord");
        Response.Write(ds.GetXml());
        File.WriteAllText(path, ds.GetXml());

The XML should look exactly like:

<?xml version="1.0" encoding="iso-8859-1"?>
<coords>
<coord id="6090">
    <title>Office 6090</title>
    <xmin>10</xmin>
    <xmax>60</xmax>
    <ymin>40</ymin>
    <ymax>90</ymax>
    <desc>
        <brief>one</brief>
        <long>one more</long>
        <img>dude.jpg</img>
    </desc>
</coord>
<coord id="11090">....

The Response.Write code writes it out to the page correctly. However, when I try to write to a file, it gets changed to what seems like htmlencoding.

 &lt;coords xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;&lt

I don't see a way to just write the same text that's rendered during response.write. Any clues would be appreciated.

Upvotes: 0

Views: 305

Answers (3)

code4life
code4life

Reputation: 15794

Change your approach. Sorry, I didn't pick up on the fact that you were using the FOR XML clause.

In this case, you must use the ExecuteXmlReader, and save the resulting output. Here's an example:

var xmlReader = cmd.ExecuteXmlReader();
var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
xmlReader.Close();
xmlDoc.Save(path);

Hope this helps!

Upvotes: 1

Khan
Khan

Reputation: 18162

Have you tried ds.WriteXml(string path) ?

Reference: http://msdn.microsoft.com/en-us/library/hb27k0tf.aspx


If you have the option, you can bypass writing the file from .net and do it sql side

bcp "SELECT * FROM pubs..authors FOR XML RAW" queryout c:\myfile.xml -Sserver -Uusername -Ppassword -c -r -t

Reference: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=9336

Upvotes: 0

user1308985
user1308985

Reputation: 81

Try using the HtmlDecode method on your output. http://msdn.microsoft.com/en-us/library/7c5fyk1k.aspx

Upvotes: 0

Related Questions