XmlWriter writing empty stringbuilder - c#

I had the following code which "worked" for my testing but I didn't like the formatting:
System.Diagnostics.Debug.WriteLine("----------------------------- Start 1 ----------------------------");
using (var sw = new Utf8StringWriter())
//StringBuilder sb = new StringBuilder();
//using (XmlWriter xw = XmlWriter.Create(sb, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }))
{
XDocument d = new XDocument(new XDeclaration(version: "1.0", encoding: "UTF-8", standalone: "no"));
XElement DMTStandardIF = new XElement("DMTStandardIF", new XAttribute("version", "1.00"));
d.Add(DMTStandardIF);
XElement last = DMTStandardIF;
last.Add(last = new XElement("Thing1", "thing 1 stuff"));
last.Add(null);
last.Add(last = new XElement("Thing2", "thing 2 stuff"));
last.Add(null);
d.Save(sw);
//d.WriteTo(xw);
System.Diagnostics.Debug.WriteLine(sw);
//System.Diagnostics.Debug.WriteLine(sb.ToString());
}
// So I changed it to the following which outputs nothing; xw has content but sb is empty.
System.Diagnostics.Debug.WriteLine("----------------------------- Start 2 ----------------------------");
StringBuilder sb = new StringBuilder();
using (XmlWriter xw = XmlWriter.Create(sb, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }))
{
XDocument d = new XDocument(new XDeclaration(version: "1.0", encoding: "UTF-8", standalone: "no"));
XElement DMTStandardIF = new XElement("DMTStandardIF", new XAttribute("version", "1.00"));
d.Add(DMTStandardIF);
XElement last = DMTStandardIF;
last.Add(last = new XElement("Thing1", "thing 1 stuff"));
last.Add(null);
last.Add(last = new XElement("Thing2", "thing 2 stuff"));
last.Add(null);
d.WriteTo(xw);
//d.Save(xw); // I tried this too and .. empty as well
System.Diagnostics.Debug.WriteLine(sb.ToString());
}
System.Diagnostics.Debug.WriteLine("------------------------------ Done ------------------------------");
Here's what you'll get if you run that:
----------------------------- Start 1 ----------------------------
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<DMTStandardIF version="1.00">
<Thing1>thing 1 stuff<Thing2>thing 2 stuff</Thing2></Thing1>
</DMTStandardIF>
----------------------------- Start 2 ----------------------------
------------------------------ Done ------------------------------
WHY does the second version output nothing? How do I fix it?
This all started because I wanted to test what happens if I attempt myXElement.Add(null) and I already answered that question but I saw XmlWriter writing empty down the rabbit hole and went after it.

Your code doesn't print anything because when you call the Debug.WriteLine the StringBuilder has not yet received the buffer from the XmlWriter. This happens (probably with a call to xw.Flush()) when your code exits from the using statement
Just move the print of the StringBuilder outside the using statement
using (XmlWriter xw = XmlWriter.Create(sb, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }))
{
....
d.WriteTo(xw);
}
System.Diagnostics.Debug.WriteLine(sb.ToString());
System.Diagnostics.Debug.WriteLine("------------------------------ Done --------------------");
In alternative you can force a Flush on the XmlWriter inside the using statement just before printing the StringBuilder.
using (XmlWriter xw = XmlWriter.Create(sb, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }))
{
....
d.WriteTo(xw);
xw.Flush();
System.Diagnostics.Debug.WriteLine(sb.ToString());
}
System.Diagnostics.Debug.WriteLine("------------------------------ Done --------------------");
But in this context it seems pointless and redundant (it will be called again) considering that the code exits the using statement just on the next line.

Related

XML Writer - Unable to override UTF16 to UTF8

I'm trying to build the XML using XMLWriter but it contains encoding UTF-16. I tried so solution to modify that to UTF-8. But nothing is working
var settings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(true),
Indent = false,
OmitXmlDeclaration = false,
NewLineHandling = NewLineHandling.None
};
Try to override the UTF8String Writer
private class UTF8StringWriter : StringWriter
{
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
Try to use XDEclaration.
var doc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("root", new XAttribute("note", "boogers"))
);
using (var writer = new XmlTextWriter(".\\test.xml", new UTF8Encoding(false)))
{
doc.Save(writer);
}

preview my XML StringWriter in default browser

Good morning everyone. I wrote a very simple class in C# that generates an html file and return it in a string. I want to write a new class that will display this file in default browser. Could you tell me how can I do it?
public class Class1
{
public string HTMLGen(int number)
{
var html = string.Format("<p>testing my {0} html code</p>", number);
var xDocument = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html",
new XElement("head"),
new XElement("body",
XElement.Parse(html)
)
)
);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "\t"
};
using (var sw = new StringWriter())
{
using (var writer = XmlWriter.Create(sw, settings))
{
xDocument.WriteTo(writer);
}
return sw.ToString();
}
}
}

Add An XML Declaration To String Of XML

I have some xml data that looks like..
<Root>
<Data>Nack</Data>
<Data>Nelly</Data>
</Root>
I want to add "<?xml version=\"1.0\"?>" to this string. Then preserve the xml as a string.
I attempted a few things..
This breaks and loses the original xml string
myOriginalXml="<?xml version=\"1.0\"?>" + myOriginalXml;
This doesnt do anything, just keeps the original xml data with no declaration attached.
XmlDocument doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8","no");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string xmlString = sw.ToString();
This is also not seeming to have any effect..
XmlDocument doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
MemoryStream xmlStream = new MemoryStream();
doc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position = 0;
doc.Load(xmlStream);
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string xmlString = sw.ToString();
Use an xmlwritersettings to achieve greater control over saving. The XmlWriter.Create accepts that setting (instead of the default contructor)
var myOriginalXml = #"<Root>
<Data>Nack</Data>
<Data>Nelly</Data>
</Root>";
var doc = new XmlDocument();
doc.LoadXml(myOriginalXml);
var ms = new MemoryStream();
var tx = XmlWriter.Create(ms,
new XmlWriterSettings {
OmitXmlDeclaration = false,
ConformanceLevel= ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8 });
doc.Save(tx);
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());

remove encoding from xmlserializer

I am using the following code to create an xml document -
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
new XmlSerializer(typeof(docket)).Serialize(Console.Out, i, ns);
this works great in creating the xml file with no namespace attributes. i would like to also have no encoding attribute in the root element, but I cannot find a way to do it. Does anyone have any idea if this can be done?
Thanks
Old answer removed and update with new solution:
Assuming that it's ok to remove the xml declaration completly, because it makes not much sense without the encoding attribute:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");
using (XmlWriter writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { OmitXmlDeclaration = true}))
{
new XmlSerializer(typeof (SomeType)).Serialize(writer, new SomeType(), ns);
}
To remove encoding from XML header pass TextWriter with null encoding to XmlSerializer:
MemoryStream ms = new MemoryStream();
XmlTextWriter w = new XmlTextWriter(ms, null);
s.Serialize(w, vs);
Explanation
XmlTextWriter uses encoding from TextWriter passed in constructor:
// XmlTextWriter constructor
public XmlTextWriter(TextWriter w) : this()
{
this.textWriter = w;
this.encoding = w.Encoding;
..
It uses this encoding when generating XML:
// Snippet from XmlTextWriter.StartDocument
if (this.encoding != null)
{
builder.Append(" encoding=");
...
string withEncoding;
using (System.IO.MemoryStream memory = new System.IO.MemoryStream()) {
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(memory)) {
serializer.Serialize(writer, obj, null);
using (System.IO.StreamReader reader = new System.IO.StreamReader(memory)) {
memory.Position = 0;
withEncoding= reader.ReadToEnd();
}
}
}
string withOutEncoding= withEncoding.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
Credit to this blog for helping me with my code
http://blog.dotnetclr.com/archive/2008/01/29/removing-declaration-and-namespaces-from-xml-serialization.aspx
here's my solution, same idea, but in VB.NET and a little clearer in my opinion.
Dim sw As StreamWriter = New, StreamWriter(req.GetRequestStream,System.Text.Encoding.ASCII)
Dim xSerializer As XmlSerializer = New XmlSerializer(GetType(T))
Dim nmsp As XmlSerializerNamespaces = New XmlSerializerNamespaces()
nmsp.Add("", "")
Dim xWriterSettings As XmlWriterSettings = New XmlWriterSettings()
xWriterSettings.OmitXmlDeclaration = True
Dim xmlWriter As XmlWriter = xmlWriter.Create(sw, xWriterSettings)
xSerializer.Serialize(xmlWriter, someObjectT, nmsp)

Force XDocument to write to String with UTF-8 encoding

I want to be able to write XML to a String with the declaration and with UTF-8 encoding. This seems mighty tricky to accomplish.
I have read around a bit and tried some of the popular answers for this but the they all have issues. My current code correctly outputs as UTF-8 but does not maintain the original formatting of the XDocument (i.e. indents / whitespace)!
Can anyone offer some advice please?
XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xelementXML);
MemoryStream ms = new MemoryStream();
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String xmlString = sr.ReadToEnd();
}
The XML requires the formatting to be identical to the way .ToString() would format it i.e.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<node>blah</node>
</root>
What I'm currently seeing is
<?xml version="1.0" encoding="utf-8" standalone="yes"?><root><node>blah</node></root>
Update
I have managed to get this to work by adding XmlTextWriter settings... It seems VERY clunky though!
MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String blah = sr.ReadToEnd();
}
Try this:
using System;
using System.IO;
using System.Text;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml",
LoadOptions.PreserveWhitespace);
doc.Declaration = new XDeclaration("1.0", "utf-8", null);
StringWriter writer = new Utf8StringWriter();
doc.Save(writer, SaveOptions.None);
Console.WriteLine(writer);
}
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
}
Of course, you haven't shown us how you're building the document, which makes it hard to test... I've just tried with a hand-constructed XDocument and that contains the relevant whitespace too.
Try XmlWriterSettings:
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = false;
xws.Indent = true;
And pass it on like
using (XmlWriter xw = XmlWriter.Create(sb, xws))
See also https://stackoverflow.com/a/3288376/1430535
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();

Categories