I've been stuck with this problem for a few hours and can't seem to figure it out, so I'm asking here :)
Alright, I've got this function:
private void XmlDump()
{
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement rootElement = new XElement("dump");
rootElement.Add(TableToX("Support"));
string connectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "select * from support";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet("Test");
da.Fill(ds, "support");
// Convert dataset to XML here
var docresult = // Converted XML
Response.Write(docResult);
Response.ContentType = "text/xml; charset=utf-8";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xml");
Response.End();
}
I've been trying all kind of different things but I keep getting errors, so I've left the how to convert DataSet to XML part blank.
And another thing, this query contains columns with special characters.
You can use ds.WriteXml, but that will require you to have a Stream to put the output into. If you want the output in a string, try this extension method:
public static class Extensions
{
public static string ToXml(this DataSet ds)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(DataSet));
xmlSerializer.Serialize(streamWriter, ds);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}
}
USAGE:
var xmlString = ds.ToXml();
// OR
Response.Write(ds.ToXml());
Simply use Dataset.getXml():
doc.LoadXml(ds.GetXml());
Write like below code part
DataTable dt = new DataTable("MyData");
dt.WriteXml(#Application.StartupPath + "\\DataBaseValues.xml");
Or, You can convert directly the dataSet also as said by Oded like,
private void WriteXmlToFile(DataSet thisDataSet)
{
if (thisDataSet == null)
{
return;
}
// Create a file name to write to.
string filename = "myXmlDoc.xml";
// Create the FileStream to write with.
System.IO.FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
// Create an XmlTextWriter with the fileStream.
System.Xml.XmlTextWriter myXmlWriter =
new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}
Use DataSet.WriteXml - it will output the dataset as XML.
if ds is your dataset..
you can use:
ds.getXml();
this helps in getting XML
We can use this also
Private Function DsToXML(DataSet ds) as System.Xml.XmlDataDocument
Dim xmlDoc As System.Xml.XmlDataDocument
Dim xmlDec As System.Xml.XmlDeclaration
Dim xmlWriter As System.Xml.XmlWriter
xmlWriter = New XmlTextWriter(context.Response.OutputStream,System.Text.Encoding.UTF8)
xmlDoc = New System.Xml.XmlDataDocument(ds)
xmlDoc.DataSet.EnforceConstraints = False
xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
xmlDoc.PrependChild(xmlDec)
xmlDoc.WriteTo(xmlWriter)
Retuen xmlDoc
End Eunction
Try this. It worked for me.
static XmlDocument xdoc = new XmlDocument(); //static; since i had to access this file someother place too
protected void CreateXmlFile(DataSet ds)
{
//ds contains sales details in this code; i.e list of products along with quantity and unit
//You may change attribute acc to your needs ; i.e employee details in the below code
string salemastid = lbl_salemastid.Text;
int i = 0, j=0;
String str = "salemastid:" + salemastid;
DataTable dt = ds.Tables[0];
string xml = "<Orders>" ;
while (j < dt.Rows.Count)
{
int slno = j + 1;
string sl = slno.ToString();
xml += "<SlNo>" + sl +"</SlNo>" +
"<PdtName>" + dt.Rows[j][0].ToString() + "</PdtName>" +
"<Unit>" + dt.Rows[j][1].ToString() + "</Unit>" +
"<Qty>" + dt.Rows[j][2].ToString() + "</Qty>";
j++;
}
xml += "</Orders>";
xdoc.LoadXml(xml);
//Here the xml is prepared and loaded in xml DOM.
xdoc.Save(Server.MapPath("Newsales.xml"));
//You may also use some other names instead of 'Newsales.xml'
//to get a downloadable file use the below code
System.IO.MemoryStream stream = new System.IO.MemoryStream();
XmlTextWriter xwriter = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
xdoc.WriteTo(xwriter);
xwriter.Flush();
Response.Clear();
Encoding.UTF8.GetString(stream.ToArray());
byte[] byteArray = stream.ToArray();
Response.AppendHeader("Content-Disposition", "filename=OrderRequest.xml");
Response.AppendHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(byteArray);
xwriter.Close();
stream.Close();
}
Related
I have 15k records in datatable and I am unable to convert datatable to xml, getting outofmemory exception in asp.net c#.
XmlDocument xmlDoc = new XmlDocument();
using (MemoryStream memoryStream = new MemoryStream()) {
using (TextWriter streamWriter = new StreamWriter(memoryStream)) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataTable));
xmlSerializer.Serialize(streamWriter, dt);
if (memoryStream.Position > 0) {
memoryStream.Position = 0;
}
xmlDoc.Load(memoryStream);
}
}
you can try use this method DataTable.WriteXml if your version .net is permit this
DataSet ds = new DataSet();
DataTable customerTable = GetCustomers();
DataTable orderTable = GetOrders();
ds.Tables.Add(customerTable);
ds.Tables.Add(orderTable);
ds.Relations.Add("CustomerOrder",
new DataColumn[] { customerTable.Columns[0] },
new DataColumn[] { orderTable.Columns[1] }, true);
System.IO.StringWriter writer = new System.IO.StringWriter();
customerTable.WriteXml(writer, XmlWriteMode.WriteSchema, false);
I have TextBlock with name XML_View, also I know .xml file location string filename = dlg.FileName;
So I want to show xml n that TextBlock, I found a possible solution here (Display XML in a WPF textbox), it gives as a function, like this:
protected string FormatXml(string xmlString)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
StringBuilder sb = new StringBuilder();
System.IO.TextWriter tr = new System.IO.StringWriter(sb);
XmlTextWriter wr = new XmlTextWriter(tr);
wr.Formatting = Formatting.Indented;
doc.Save(wr);
wr.Close();
return sb.ToString();
}
If I get required string, I might just simply write XML_View.Text = String_xml; or something like this. But I don't know how to get string if I have .xml file and I don't know how to use such a function.
I've modified your function to take as parameter the filename to read your xml from. Make sure the file exists in your bin directory (or you use an absolute path like #"C:\temp\myfile.xml" to resolve).
protected string FormatXml(string xmlFile)
{
XmlDocument doc = new XmlDocument();
FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
doc.Load(fs);
StringBuilder sb = new StringBuilder();
System.IO.TextWriter tr = new System.IO.StringWriter(sb);
XmlTextWriter wr = new XmlTextWriter(tr);
wr.Formatting = Formatting.Indented;
doc.Save(wr);
wr.Close();
return sb.ToString();
}
You can replace
doc.LoadXml(xmlString);
with
doc.Load(xmlFilePath);
I used this as reference.
I am sure this is an easy question however I am not finding the solution. I want to save the XML files posted to my .NET Web Service. I am sure it is just a simple method call when the service is invoked but I am not finding it. I would like to save the full XML posted to the service
Any help would be greatly appreciated. Thank you in advance.
Thank you for your help however I found what I was looking for at http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx
To help anyone else that is new to tring to implement this via WebService's I included the steps that I performed to implement it and modifications so I could save it to the db as well as the file system I performed the following steps. If you have any questions please feel free to aks and I will be happy to answer.
Created a code file in my web service project with the code listed in the in the article
Created a few properties to store values to save to the db
private string _requestXml;
private DateTime _start;
Then I modified the WriteInput method to save values to those variables.
public void WriteInput(SoapMessage message)
{
//Begin Edit
oldStream.Position = 0;
_requestXml = new StreamReader(_oldStream).ReadToEnd();
_start = DateTime.UtcNow;
//End Edit
//Begin Original Code
oldStream.Position = 0;
Copy(oldStream, newStream);
var fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
var w = new StreamWriter(fs);
var soapString = (message is SoapServerMessage) ? "SoapRequest" : "SoapResponse";
w.WriteLine("-----" + soapString + " at " + DateTime.Now);
w.Flush();
newStream.Position = 0;
Copy(newStream, fs);
w.Close();
newStream.Position = 0;
}
Then I modified the WriteOutput to
public void WriteOutput(SoapMessage message)
{
//Begin Edit
var responseXml = new StreamReader(newStream).ReadToEnd();
newStream.Position = 0;
//Start process for saving to DB
//"_requestXml" = Original Request Soap Message
//"responseXml" = Service Returned Response
//"_start" = Request Start Time
//message.MethodInfo.Name = I save this so I know what method from
//message.Url = I save this so I know the original ASMX that was hit
//End Edit
//Begin Original Code
newStream.Position = 0;
var fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
var w = new StreamWriter(fs);
var soapString = (message is SoapServerMessage) ? "SoapResponse" : "SoapRequest";
w.WriteLine("-----" + soapString + " at " + DateTime.Now);
w.Flush();
Copy(newStream, fs);
w.Close();
newStream.Position = 0;
Copy(newStream, oldStream);
}
Now all that's left is to add the following to your service call and you should be good to go
[WebMethod, NameSpace.OfyourTraceExtesionClass.TraceExtension]
public void WebMethod1()
{
//DoSomeStuff
}
If you want to log the http post messages, an elegant way of solving it would be to set up a simple reverse proxy in front of your web services. In this proxy you would have full access to the raw http request.
XML file received as Stream
Convert Stream to byte[]
Convert byte[] to XDocument (System.Xml.Linq)
Read XDocument with LINQ syntax and save to DB
[WebMethod]
public void XMLPersing()
{
var XMLDATA = "";
WriteLogCLS objWriteLog = new WriteLogCLS();
Stream receiveStream = HttpContext.Current.Request.InputStream;
receiveStream.Position = 0;
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); //For xml persing..
XMLDATA = readStream.ReadToEnd();
readStream.Close();
objWriteLog.WriteLog(Convert.ToString(XMLDATA));
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Log/Exception/Sample.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
var strCon = string.Empty;
strCon = ConfigurationManager.AppSettings["constring"];
SqlCommand cmdInsertXMLData = new SqlCommand();
SqlConnection SqlConn;
SqlConn = new SqlConnection(strCon);
try
{
cmdInsertXMLData = new SqlCommand("usp_InsertXML", SqlConn);
cmdInsertXMLData.CommandType = CommandType.StoredProcedure;
// cmdInsertLoginDetails.Parameters.Add("#XMLdata", SqlDbType.Xml).Value = ds.GetXml();
cmdInsertXMLData.Parameters.AddWithValue("#XMLdata", SqlDbType.Xml);
if (SqlConn.State == ConnectionState.Closed)
{
SqlConn.Open();
}
cmdInsertXMLData.ExecuteNonQuery();
// response = cmdInsertLoginDetails.Parameters["#Message"].Value.ToString();
}
catch (Exception ex)
{
objWriteLog.WriteLog("Error on XML Persing : " + ex.Message);
// response = "Error";
}
finally
{
if (cmdInsertXMLData != null)
{
cmdInsertXMLData.Dispose();
}
if (SqlConn.State == ConnectionState.Open)
{
SqlConn.Close();
SqlConn.Dispose();
}
objWriteLog = null;
}
// return response ;
}
}
}
I'm tring to get a string from a DataSet without using GetXml. I'm using WriteXml, instead. How to use it to get a string?
Thanks
StringWriter sw = new StringWriter();
dataSet.WriteXml(sw);
string result = sw.ToString();
Write to a StringWriter, and then call ToString on that.
Note that if you want the generated XML declaration to specify UTF-8 instead of UTF-16, you'll need something like my Utf8StringWriter.
here is the vb.net code:
Private Function GenerateXML(ByVal ds As DataSet) As String
Dim obj As New StringWriter()
Dim xmlstring As String
ds.WriteXml(obj)
xmlstring = obj.ToString()
Return xmlstring
End Function
public string ConvertDatatableToXML(DataTable dt)
MemoryStream str = new MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstring = "";
xmlstring = sr.ReadToEnd();
return (xmlstring);
I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.
I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
From the article:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Edit:
But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
Here is a tutorial about how to do XSL Transformations in C# on MSDN:
http://support.microsoft.com/kb/307322/en-us/
and here how to write files:
http://support.microsoft.com/kb/816149/en-us
just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):
http://support.microsoft.com/kb/307379/en-us/
i added this just to provide some more information.
This might help you
public static string TransformDocument(string doc, string stylesheetPath)
{
Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContent);
return xmlDocument;
};
try
{
var document = GetXmlDocument(doc);
var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(style); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
I would like to share this small piece of code which reads from Database and transforms using XSLT. On the top I also have used xslt-extensions which makes it little different than others.
Note: This is just a draft code and may need cleanup before using in production.
var schema = XDocument.Load(XsltPath);
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var command = new SqlCommand(Sql, connection))
{
var reader = command.ExecuteReader();
var dt = new DataTable(SourceNode);
dt.Load(reader);
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine;
using (var stringWriter = new StringWriter())
{
dt.WriteXml(stringWriter, true);
xml += stringWriter.GetStringBuilder().ToString();
}
XDocument transformedXml = new XDocument();
var xsltArgumentList = new XsltArgumentList();
xsltArgumentList.AddExtensionObject("urn:xslt-extensions", new XsltExtensions());
using (XmlWriter writer = transformedXml.CreateWriter())
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(schema.CreateReader());
xslt.Transform(XmlReader.Create(new StringReader(xml)), xsltArgumentList, writer);
}
var result = transformedXml.ToString();
}
}
XsltPath is path to your xslt file.
ConnectionString constant is pointing to your database.
Sql is your query.
SourceNode is node of each record in source xml.
Now the interesting part, please note the use of urn:xslt-extensions and new XsltExtensions() in above code. You can use this if need some complex computation which may not be possible in xslt. Following is a simple method to format date.
public class XsltExtensions
{
public string FormatDate(string dateString, string format)
{
DateTime date;
if (DateTime.TryParse(dateString, out date))
return date.ToString(format);
return dateString;
}
}
In XSLT file you can use it as below;
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="urn:xslt-extensions">
...
<myTag><xsl:value-of select="ext:FormatDate(record_date, 'yyyy-MM-dd')"/></myTag>
...
</xsl:stylesheet>