views:

487

answers:

2

Here's some C# code:

var sb = new StringBuilder();
var w = XmlWriter.Create(sb);
w.WriteStartElement("hello");
w.WriteAttributeString("target", "world ' \" !");
w.WriteEndElement();
w.Flush();
// then look at sb.ToString()

I'm getting a string that looks like:

 <?xml version="1.0" encoding="utf-16"?><hello target="world ' &quot; !" />

It's only escaping the double-quote, not the single-quote. But the docs for XmlWriter.WriteAttributeString(String, String) say:

If the attribute value includes double or single quotes, they are replaced with &quot; and &apos; respectively.

Is there some flag I need to set to make it do what the docs say it does?

+6  A: 

If you use .Net Reflector to look at the code, you'll find that the System.Xml.XmlTextEncoder.Write(string) method is being called. Here's the code of interest:

if (!this.inAttribute || (this.quoteChar != ch))
   this.textWriter.Write('\'');
else
   this.WriteEntityRefImpl("apos");

When writing an attribute value, a single quote is not escaped since it doesn't need to be. It's only when writing a text element that "&apos;" is used.

David
A: 

This isn't a bug in the XmlWriter, it's a bug in your legacy system.

If you look at the definition of AttValue in the XML 1.0 recommendation, you'll see that the XmlWriter is doing exactly what it's supposed to be doing: if the attribute value is delimited with apostrophes, an attribute value can contain quotation marks, and if it's delimited with quotation marks, an attribute value can contain apostrophes.

You could, conceivably, derive a class from XmlTextWriter and override its WriteAttributes and WriteAttributeString methods. That might work. Watch out for namespaces and encoding if you do this, though.

Robert Rossney
When the official docs say a method should do something, and it doesn't, I call that a bug. YMMV. :-)
Ken
Sure, but that's a bug in the docs. They're trying to be too helpful. What the docs *ought* to note is implementation-specific behavior, e.g. the fact that the method escapes > even though the XML recommendation doesn't require it.
Robert Rossney