I need to overwrite the XMLWriter's method "WriteElementString" to not write the element if the value is empty, the code bellow didn't work, tried override and new keywords but it still goes to the framework method.
public static void WriteElementString(this XmlWriter writer,
string localName,
string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
writer.WriteStartElement(localName);
writer.WriteString(value);
writer.WriteEndElement();
}
}
The answer was close but correct solution is:
public abstract class MyWriter : XmlWriter
{
private readonly XmlWriter writer;
public Boolean skipEmptyValues;
public MyWriter(XmlWriter writer)
{
if (writer == null) throw new ArgumentNullException("Writer");
this.writer = writer;
}
public new void WriteElementString(string localName, string value)
{
if (string.IsNullOrWhiteSpace(value) && skipEmptyValues)
{
return;
}
else
{
writer.WriteElementString(localName, value);
}
}
}
You need to create an object that decorates
XmlWriter
to achieve what you are trying to do. More on the Decorator PatternWhat you are trying to do, is to override a method using an extension method which is not what they are intended to do. See the Binding Extension Methods at Compile Time section on the Extension Methods MSDN Page The compiler will always resolve
WriteElementString
to the instance implemented byXmlWriter
. You would need to manually call your extension methodXmlWriterExtensions.WriteElementString(writer, localName, value);
in order for your code to execute as you have it.