Net 2.0 XmlWriter Create and Attributes

G

Guest

The following two cases behave differently in Net 2.0. The
Case_Create_StringWriter throws an exception while the Case_XmlTextWriter
does not.

Is there a problem with this code?
Or is this a known problem?

--------------------------------------------------------------------------
using System;
using System.Xml;
using System.Text;

namespace TestXmlNil2005
{
class Program
{
static void Main(string[] args)
{
Case_XmlTextWriter();
Case_Create_StringWriter();
}

static void Case_Create_StringWriter()
{
try
{
System.IO.StringWriter sw = new System.IO.StringWriter();

XmlWriter xw = XmlWriter.Create(sw);

WriteXml(xw);

System.Console.WriteLine("xml Create-StringWriter=" + sw.ToString());
}
catch (Exception e)
{
System.Console.WriteLine("xml Create-StringWriter=exception = " +
e.Message);
}
}

static void Case_XmlTextWriter()
{
System.IO.StringWriter sw = new System.IO.StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);

WriteXml(xw);

System.Console.WriteLine("xml XmlTextWriter=" + sw.ToString());
}

static void WriteXml(XmlWriter xw)
{
xw.WriteStartElement("document");

xw.WriteAttributeString("xsi:nil", "true");

xw.WriteEndElement();
xw.Flush();
xw.Close();
}

}
}
 
D

Derrick Coetzee [MSFT]

jschell said:
The Case_Create_StringWriter throws an exception [...]

static void Case_Create_StringWriter() {
System.IO.StringWriter sw = new System.IO.StringWriter();
XmlWriter xw = XmlWriter.Create(sw);
WriteXml(xw);
}

static void WriteXml(XmlWriter xw) {
xw.WriteStartElement("document");
xw.WriteAttributeString("xsi:nil", "true");
xw.WriteEndElement();
xw.Flush();
xw.Close();
}

The problem is that you can't specify a namespace using the ns:name syntax
directly in this way. Instead, use an overload of WriteAttributeString()
which explicitly takes both a namespace and name:

xw.WriteAttributeString("xsi","nil","http://uri.of.xsi.namespace/","true");

The reason that your original code mysteriously works for XmlTextWriter but
not XmlWriter is that XmlWriter sets the CheckCharacters attribute of its
XmlWriterSettings instance to true by default, which causes it to check for
invalid characters that XmlTextWriter does not have the ability to check
for. You can read more here:

http://msdn2.microsoft.com/en-us/library/kkz7cs0d.aspx

I hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top