Reputation: 5224
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 ' " !" />
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 " and ' respectively.
Is there some flag I need to set to make it do what the docs say it does?
Upvotes: 1
Views: 3985
Reputation: 96722
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.
Upvotes: 2
Reputation: 34563
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 "'" is used.
Upvotes: 7