What is the best way to create xml file in .net 2.0 in terms of nodes etc. I dont think I could use LINQ. Any code sample or article would be helpful.
You best bet is to use the XmlTextWriter class.
Here's a pretty basic example:
var writer = new XmlTextWriter("Foo.xml", Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Foo");
writer.WriteAttributeString("hello", "world");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
This will give you:
<?xml version="1.0" encoding="utf-8"?>
<Foo hello="world" />
Here's a code snippet that works:
XmlTextWriter myXW = new XmlTextWriter(#"C:\NewXmlFile.xml", Encoding.UTF8)
myXW.WriteStartDocument();
myXW.WriteStartElement("Customers");
string strConn = myConnectionString;
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand myCMD = new OleDbCommand("select * from customers", myConn);
OleDbDataReader myRdr = myCMD.ExecuteReader();
while (myRdr.Read())
{
myXW.WriteStartElement("Customer");
myXW.WriteAttributeString("id", myRdr.GetString(0));
myXW.WriteElementString("companyname", myRdr.GetString(1));
myXW.WriteElementString("contactname", myRdr.GetString(2));
myXW.WriteElementString("contactname", myRdr.GetString(3));
myXW.WriteElementString("address", myRdr.GetString(4));
myXW.WriteElementString("city", myRdr.GetString(5));
myXW.WriteElementString("country", myRdr.GetString(8));
myXW.WriteElementString("phone", myRdr.GetString(9));
myXW.WriteElementString("fax", myRdr.GetString(10));
myXW.WriteEndElement();
}
myXW.WriteEndElement();
myXW.WriteEndDocument();
myXW.Flush();
myXW.Close();
Related
I'm trying to insert a xml file that I read from a stream into a column of type xml in mssql server
like this:
//read file from stream
var reader = new StreamReader(request.InputStream, Encoding.UTF8);
var string = reader.ReadToEnd();
//convert to xmldoc
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(string);
//Try to inser it into the table using the xmlDoc
using (SqlConnection con = new SqlConnection(_connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(
#"INSERT INTO [XMLTable] (XmlData) VALUES(#XmlData);", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#XmlData", xmlDoc.InnerXml);
cmd.ExecuteScalar();
}
}
//Sample xml :
<?xml version="1.0" encoding="utf-8"?>
<ChangeSSNR version="1.0" xmlns="http://schemas.testschema.com/ChangeSSNR/1.0/">
<Header version="1.0">
<From>someone</From>
<To>someoneelse</To>
<TimeStamp>1900-01-01T01:01:01+01:00</TimeStamp>
<ppnSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />
</Header>
<ChangeSSNRid id="4294967295">
<SSNRChange>
<NewSSNR>09834098098</NewSSNR>
<OldSSNR>9879879827345</OldSSNR>
</SSNRChange>
</ChangeSSNRid>
<ChangeSSNRid id="42949367295">
<SSNRChange>
<NewSSNR>098340980983</NewSSNR>
<OldSSNR>98798798273453</OldSSNR>
</SSNRChange>
</ChangeSSNRid>
</ChangeSSNR>
Getting an exception : XML parsing: line 1, character 38, unable to switch the encoding
Kind Regards
/Rudy
The XML file shouldn't have any leading spaces on the first line:
XML
<?xml version="1.0" encoding="utf-8"?>
<ChangeSSNR version="1.0" xmlns="http://schemas.testschema.com/ChangeSSNR/1.0/">
<Header version="1.0">
<From>someone</From>
<To>someoneelse</To>
<TimeStamp>1900-01-01T01:01:01+01:00</TimeStamp>
<ppnSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:nil="true"/>
</Header>
<ChangeSSNRid id="4294967295">
<SSNRChange>
<NewSSNR>09834098098</NewSSNR>
<OldSSNR>9879879827345</OldSSNR>
</SSNRChange>
</ChangeSSNRid>
<ChangeSSNRid id="42949367295">
<SSNRChange>
<NewSSNR>098340980983</NewSSNR>
<OldSSNR>98798798273453</OldSSNR>
</SSNRChange>
</ChangeSSNRid>
</ChangeSSNR>
It is better to use LINQ to XML while dealing with XML. It is available in the .Net Framework since 2007.
c#
...
XDocument xdoc = XDocument.Parse(string);
...
cmd.Parameters.AddWithValue("#XmlData", xdoc.ToString());
I am simply trying to load a dataset and output it on a webpage as XML with the schema being written as well. I have been researching to find a way to achieve this without any luck.
The code I am using is:
string str =
"SELECT Name,Members,MaxLvl,Faction,Government,Score FROM dim5orgs where faction =
'Omni' order by Score DESC";
// Connection string for a typical local MySQL installation
string cnnString = "Server=xxxxxxxnet;Port=3306;Database=xxx;Uid=xxxxx;Pwd=xxxx";
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
// Create a SQL command object
string cmdText = str;
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
// Create a fill a Dataset
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
StringWriter sw = new StringWriter();
ds.WriteXml(sw,XmlWriteMode.WriteSchema);
string result = sw.ToString();
Response.Write(result);
Right now I am getting output like:
Punk732220OmniRepublic1644786805740
Paradise754220OmniDepartment1633903815782
I would like the output to be in proper XML form somehow using the column names in the dataset.
Like:
<data>
<name>Punk</name>
<members>732</members>
<Maxlvl>220</MaxLvl>...etc
</data>
I would like to be in proper XML form, with the XML headers written properly.
Thank you.
Look into the documentation of the XmlSerializer Class. I think you could use it something like this:
StreamWriter streamWriter = new StreamWriter(fileLocation);
XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(ds.GetType());
xml.Serialize(streamWriter, ds);
streamWriter.Close();
I have not tried it with DataSets so I'm not sure.
When you say "I am getting output like", does that mean you are seeing that in your webpage, or that is what "result" contains when you debug the program?
If the former, you are probably missing setting the response type:
Response.ContentType = "text/xml";
and optionally the encoding:
Response.ContentEncoding = System.Text.Encoding.UTF8;
before you write your response.
EDIT: Also, make sure you are not returning any html from your page template or master page (assuming you are using .aspx files). You can check this by looking at your page source in your browser (right click and "view source" in IE). Apologies if this teaching you to suck eggs, from your question I didn't know if you have already checked these things or not.
Edit 2: I've tested your code, and if you set the response ContentType to text/xml it works for me.
I am calling oracle package, to get xml file from the package into oracleDataReader. How can i load that into xmldocument?
Here is the code:
OracleDataReader reader = new OracleDataReader();
//calling package here and reading xml file into reader...
reader = cmd.ExecuteReader();
while(reader.Read())
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("what should i enter here to add the reader xml file???");
}
try
doc.LoadXml(reader.GetString(0));
IF the above does not work for you please provide information on the statement that is run by cmd and the DB structure/field definition etc.
I have an dataset which i need to convert to xml with encoding="UTF-8 " specifiedin the xml file
SqlConnection con = new SqlConnection(dbconn);
con.Open();
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from employee", con);
DataSet ds = new DataSet();
cmd1.Fill(ds);
string strFileName = #"E:\Dif.xml";
MemoryStream memStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memStream, Encoding.UTF8);
ds.WriteXml(writer, XmlWriteMode.WriteSchema);
i see no xml file been written,
i wante dteh xml file to be written in this format in the heading
<?xml version="1.0" encoding="utf-8" ?>
so what is teh setting that i should be doing while converting dataset to xml.
please help me out, i ma using vs2003,.net 1.1 framework
thanks
prince
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter xmlWriter = XmlWriter.Create(strFileName, settings))
{
ds.WriteXml(xmlWriter);
xmlWriter.Close();
}
Use this can write xml with encoding:
<?xml version="1.0" encoding="utf-8"?>
As per Alex's suggestion, here is my comment as an answer:
Try using FileStream instead of MemoryStream: Your code should look like this:
FileStream fs =new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
ds.WriteXML(writer, XMLWriteMode.WriteSchema);
But also, please take a look at his anwer too, maybe the answer is a combination of both our answers.
I used flying19880517s answer and converted it to an extension method. To get the same result as the original WriteXml method I added Indent = true (otherwise your get the xml without newlines / spaces.
public static void WriteXml(this DataSet ds, string fileName, Encoding encoding)
{
using (var writer = XmlWriter.Create(fileName,
new XmlWriterSettings { Encoding = encoding, Indent = true, }))
ds.WriteXml(writer);
}
Have you tried XmlWriteMode.IgnoreSchema?
Taken from http://msdn.microsoft.com/en-us/library/system.data.xmlwritemode.aspx for XmlWriteMode.WriteSchema:
Writes the current contents of the
DataSet as XML data with the
relational structure as inline XSD
schema. If the DataSet has only a
schema with no data, only the inline
schema is written. If the DataSet does
not have a current schema, nothing is
written.
You are writing to a memory stream. Use a FileStream if you want output to disk.
Regards, Morten
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Create Excel (.XLS and .XLSX) file from C#
I have some code that generates a zip file that contains multiple CSV files and streams it back to the user (no file is saved on the server). However, I want to create an excel workbook instead (can be traditional xls or Office Open XML xlsx format) with each CSV 'file' being a spreadsheet.
How can I do this, without resorting to Office Automation on the server or a commercial 3rd party component?
You can use OleDB to generate simple tables in Excel files.
Note that you will need to generate a temp file on the server.
Example.
Note that their example is incorrect and needs to use an OleDbConnectionStringBuilder, like this:
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
if (isOpenXML)
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
else
builder.Provider = "Microsoft.Jet.OLEDB.4.0";
builder.DataSource = fileName;
builder["Extended Properties"] = "Extended Properties=\"Excel 8.0;HDR=YES;\""
using (var con = new OleDbConnection(builder.ToString())) {
...
}
The XML format for Excel is quite simple and there's absolutely no need to do any automation.
The full reference is up on MSDN: http://msdn.microsoft.com/en-us/library/aa140066(office.10).aspx
Response.ContentType = "application/vnd.ms-excel";
The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.
Get all your data in a DataGrid and then get it from it can be done with:
DataGrid.RenderControl
Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
SqlConnection cn = new SqlConnection("yourconnectionstring");
cn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn);
DataTable dt = new DataTable();
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dg.RenderControl(hw);
cn.Close();
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
You can write the excel xml by yourself. Here is a nice lib for the task, maybe it is something for you.
// Edit
Link: http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx