Bob wrote:
Thanks for your reply.
I have done a bit more investigation since posting and the problem is that I
am writing into a stringbuilder.
It was reported previously as a bug by someone else but the MS response was
that it was by design. If you are writing to a stringbuilder then you will
end up with a string and strings are always UTF-16 Q.E.D.
I find this kind of logic dangerous.
Yes - it's frankly ridiculous. They can't tell what encoding you'll end
up using for converting the text data into a binary representation.
It removes a level of control that I believe should remain with the
programmer.
Agreed.
For what ever reason, the URI that I am posting to insists on no coding
attribute.
So my logic of MakeXMLDoc -> string -> bytearray -> webrequest poststream is
now
MakeXMLDOc ->string->modified string -> bytearray WebRequest.
I am using Framework 2 and the recommendation is to use the XMLWriter.
I tried using a memorystream and a XMLWriterSettings class with encoding =
null but this didn't work.
I think what you want is this:
public class NullEncodingStringWriter : StringWriter
{
public override Encoding Encoding
{
get { return null; }
}
}
If you create one of those, pass that to the XmlTextWriter, then call
XmlDocument.Save, you'll find that it doesn't put on the encoding.
Here's a sample:
using System;
using System.IO;
using System.Text;
using System.Xml;
public class Test
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml ("<?xml version='1.0'
encoding='UTF-8'?><element>text</element>");
StringWriter sw = new EncodingStringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
doc.Save(xtw);
Console.WriteLine(sw.ToString());
}
}
public class NullEncodingStringWriter : StringWriter
{
public override Encoding Encoding
{
get { return null; }
}
}
Alternatively, if you want to go to a MemoryStream anyway (to get the
bytes out directly) you could use a StreamWriter which takes the
MemoryStream as the stream to write to and uses null as the encoding.
Unfortunately, StreamWriter prevents you from specifying a null
encoding, so you need to create a derived type which overrides the
Encoding property. Again, here's a sample:
using System;
using System.IO;
using System.Text;
using System.Xml;
public class Test
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml ("<?xml version='1.0'
encoding='UTF-8'?><element>text</element>");
MemoryStream stream = new MemoryStream();
StreamWriter writer = new NullEncodingStreamWriter (stream);
XmlTextWriter xtw = new XmlTextWriter(writer);
doc.Save(xtw);
Console.WriteLine(Encoding.UTF8.GetString(stream.T oArray()));
}
}
public class NullEncodingStreamWriter : StreamWriter
{
public override Encoding Encoding
{
get
{
return null;
}
}
public NullEncodingStreamWriter (Stream stream) : base (stream)
{
}
}
Jon