DataSet.WriteXml to string - c#

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);

Related

How to show parsed xml in TextBlock in WPF?

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.

Illegal characters in path exception when Transforming XML

I am loading XML from a file, and then I want to transform it with XSLT to HTML. For that purpose I use the overload of Transform with 2 strings as parameters and therefore I make the XML into string. (The XSL is working - checked separately). But when I try to run it - I get exception at the result parameter of the .Transform() method.
XmlDocument xml = new XmlDocument();
XslCompiledTransform xsltTrans = new XslCompiledTransform();
string htmlResult = "test";
string xmlContents;
private string getXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();
return str;
}
public String getHTMLresult()
{
xml.Load(#"L:\ProjectGroup\GK\XML documents\Parent-Child.xml");
xmlContents = getXMLAsString(xml);
xsltTrans.Load(#"L:\ProjectGroup\GK\XML documents\blah.xsl");
xsltTrans.Transform(xmlContents, htmlResult);
return htmlResult;
}
Is it because htmlResult already has a value? But if I leave it blank, or set it to null I get exception null values are not allowed. Then how can I solve this problem with illegal characters ?
This is as short as possible version, try it:
XslCompiledTransform xsltTrans = new XslCompiledTransform();
string htmlResult;
string xmlContents = #"L:\ProjectGroup\GK\XML documents\Parent-Child.xml";
public String getHTMLresult()
{
xsltTrans.Load(#"L:\ProjectGroup\GK\XML documents\blah.xsl");
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xsltTrans.Transform(xmlContents, null, xw);
htmlResult = sw.ToString();
return htmlResult;
}

Convert Dataset to XML

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();
}

Deserialize a string

Currently I'm using this code to deserialize a file
StreamReader str = new StreamReader(reply);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(imginfo));
imginfo res = (imginfo)xSerializer.Deserialize(str);
How should I modify the code if reply is a string and not a path to an xml file?
Basically, you use an XmlReader chained to a StringReader:
imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
using(var xr = XmlReader.Create(sr)) {
res = (imginfo)xSerializer.Deserialize(xr);
}
//... use "res"
or as Anders notes:
imginfo res;
using(var sr = new StringReader(xml)) // "xml" is our string containing xml
res = (imginfo)xSerializer.Deserialize(sr);
}
//... use "res"
Use StringReader instead of StreamReader. No other change needed.

Format XML string to print friendly XML string

I have an XML string as such:
<?xml version='1.0'?><response><error code='1'> Success</error></response>
There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:
<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?
You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.
string FormatXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
// Handle and throw if fatal exception here; don't just ignore them
return xml;
}
}
[using statements are ommitted for brevity]
Use XmlTextWriter...
public static string PrintXML(string xml)
{
string result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(xml);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
string formattedXml = sReader.ReadToEnd();
result = formattedXml;
}
catch (XmlException)
{
// Handle the exception
}
mStream.Close();
writer.Close();
return result;
}
This one, from kristopherjohnson is heaps better:
It doesn't require an XML document header either.
Has clearer exceptions
Adds extra behaviour options: OmitXmlDeclaration = true, NewLineOnAttributes = true
Less lines of code
static string PrettyXml(string xml)
{
var stringBuilder = new StringBuilder();
var element = XElement.Parse(xml);
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.NewLineOnAttributes = true;
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
element.Save(xmlWriter);
}
return stringBuilder.ToString();
}
The simple solution that is working for me:
XmlDocument xmlDoc = new XmlDocument();
StringWriter sw = new StringWriter();
xmlDoc.LoadXml(rawStringXML);
xmlDoc.Save(sw);
String formattedXml = sw.ToString();
Check the following link: How to pretty-print XML (Unfortunately, the link now returns 404 :()
The method in the link takes an XML string as an argument and returns a well-formed (indented) XML string.
I just copied the sample code from the link to make this answer more comprehensive and convenient.
public static String PrettyPrint(String XML)
{
String Result = "";
MemoryStream MS = new MemoryStream();
XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
XmlDocument D = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
D.LoadXml(XML);
W.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
D.WriteContentTo(W);
W.Flush();
MS.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
MS.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader SR = new StreamReader(MS);
// Extract the text from the StreamReader.
String FormattedXML = SR.ReadToEnd();
Result = FormattedXML;
}
catch (XmlException)
{
}
MS.Close();
W.Close();
return Result;
}
I tried:
internal static void IndentedNewWSDLString(string filePath)
{
var xml = File.ReadAllText(filePath);
XDocument doc = XDocument.Parse(xml);
File.WriteAllText(filePath, doc.ToString());
}
it is working fine as expected.
.NET 2.0 ignoring name resolving, and with proper resource-disposal, indentation, preserve-whitespace and custom encoding:
public static string Beautify(System.Xml.XmlDocument doc)
{
string strRetValue = null;
System.Text.Encoding enc = System.Text.Encoding.UTF8;
// enc = new System.Text.UTF8Encoding(false);
System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
xmlWriterSettings.Encoding = enc;
xmlWriterSettings.Indent = true;
xmlWriterSettings.IndentChars = " ";
xmlWriterSettings.NewLineChars = "\r\n";
xmlWriterSettings.NewLineHandling = System.Xml.NewLineHandling.Replace;
//xmlWriterSettings.OmitXmlDeclaration = true;
xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
{
doc.Save(writer);
writer.Flush();
ms.Flush();
writer.Close();
} // End Using writer
ms.Position = 0;
using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc))
{
// Extract the text from the StreamReader.
strRetValue = sr.ReadToEnd();
sr.Close();
} // End Using sr
ms.Close();
} // End Using ms
/*
System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings))
{
doc.Save(writer);
writer.Close();
} // End Using writer
strRetValue = sb.ToString();
sb.Length = 0;
sb = null;
*/
xmlWriterSettings = null;
return strRetValue;
} // End Function Beautify
Usage:
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("C:\Test.svg");
string SVG = Beautify(xmlDoc);
Customizable Pretty XML output with UTF-8 XML declaration
The following class definition gives a simple method to convert an input XML string into formatted output XML with the xml declaration as UTF-8. It supports all the configuration options that the XmlWriterSettings class offers.
using System;
using System.Text;
using System.Xml;
using System.IO;
namespace CJBS.Demo
{
/// <summary>
/// Supports formatting for XML in a format that is easily human-readable.
/// </summary>
public static class PrettyXmlFormatter
{
/// <summary>
/// Generates formatted UTF-8 XML for the content in the <paramref name="doc"/>
/// </summary>
/// <param name="doc">XmlDocument for which content will be returned as a formatted string</param>
/// <returns>Formatted (indented) XML string</returns>
public static string GetPrettyXml(XmlDocument doc)
{
// Configure how XML is to be formatted
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
, IndentChars = " "
, NewLineChars = System.Environment.NewLine
, NewLineHandling = NewLineHandling.Replace
//,NewLineOnAttributes = true
//,OmitXmlDeclaration = false
};
// Use wrapper class that supports UTF-8 encoding
StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8);
// Output formatted XML to StringWriter
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
doc.Save(writer);
}
// Get formatted text from writer
return sw.ToString();
}
/// <summary>
/// Wrapper class around <see cref="StringWriter"/> that supports encoding.
/// Attribution: http://stackoverflow.com/a/427737/3063884
/// </summary>
private sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
/// <summary>
/// Creates a new <see cref="PrettyXmlFormatter"/> with the specified encoding
/// </summary>
/// <param name="encoding"></param>
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
/// <summary>
/// Encoding to use when dealing with text
/// </summary>
public override Encoding Encoding
{
get { return encoding; }
}
}
}
}
Possibilities for further improvement:-
An additional method GetPrettyXml(XmlDocument doc, XmlWriterSettings settings) could be created that allows the caller to customize the output.
An additional method GetPrettyXml(String rawXml) could be added that supports parsing raw text, rather than have the client use the XmlDocument. In my case, I needed to manipulate the XML using the XmlDocument, hence I didn't add this.
Usage:
String myFormattedXml = null;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(myRawXmlString);
myFormattedXml = PrettyXmlFormatter.GetPrettyXml(doc);
}
catch(XmlException ex)
{
// Failed to parse XML -- use original XML as formatted XML
myFormattedXml = myRawXmlString;
}
Check the following link: Format an XML file so it looks nice in C#
// Format the XML text.
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml_document.WriteTo(xml_text_writer);
// Display the result.
txtResult.Text = string_writer.ToString();
It is possible to pretty-print an XML string via a streaming transformation with XmlWriter.WriteNode(XmlReader, true). This method
copies everything from the reader to the writer and moves the reader to the start of the next sibling.
Define the following extension methods:
public static class XmlExtensions
{
public static string FormatXml(this string xml, bool indent = true, bool newLineOnAttributes = false, string indentChars = " ", ConformanceLevel conformanceLevel = ConformanceLevel.Document) =>
xml.FormatXml( new XmlWriterSettings { Indent = indent, NewLineOnAttributes = newLineOnAttributes, IndentChars = indentChars, ConformanceLevel = conformanceLevel });
public static string FormatXml(this string xml, XmlWriterSettings settings)
{
using (var textReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(textReader, new XmlReaderSettings { ConformanceLevel = settings.ConformanceLevel } ))
using (var textWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
xmlWriter.WriteNode(xmlReader, true);
return textWriter.ToString();
}
}
}
And now you will be able to do:
var inXml = #"<?xml version='1.0'?><response><error code='1'> Success</error></response>";
var newXml = inXml.FormatXml(indentChars : "", newLineOnAttributes : false); // Or true, if you prefer
Console.WriteLine(newXml);
Which prints
<?xml version='1.0'?>
<response>
<error code="1"> Success</error>
</response>
Notes:
Other answers load the XML into some Document Object Model such as XmlDocument or XDocument/XElement, then re-serialize the DOM with indentation enabled.
This streaming solution completely avoids the added memory overhead of a DOM.
In your question you do not add any indentation for the nested <error code='1'> Success</error> node, so I set indentChars : "". Generally an indentation of two spaces per level of nesting is customary.
Attribute delimiters will be unconditionally transformed to double-quotes if currently single-quotes. (I believe this is true of other answers as well.)
Passing conformanceLevel : ConformanceLevel.Fragment allows strings containing sequences of XML fragments to be formatted.
Other than ConformanceLevel.Fragment, the input XML string must be well-formed. If it is not, XmlReader will throw an exception.
Demo fiddle here.
if you load up the XMLDoc I'm pretty sure the .ToString() function posses an overload for this.
But is this for debugging? The reason that it is sent like that is to take up less space (i.e stripping unneccessary whitespace from the XML).
Hi why don't you just try this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = false;
....
....
xmlDoc.Save(fileName);
PreserveWhitespace = false; that option can be used xml beautifier as well.

Categories

Resources