我需要重写XMLWriter的方法“WriteElementString”,如果值为空则不写入元素,下面的代码无效,尝试了“override”和“new”关键字,但仍然会跳转到框架方法。
答案很接近,但正确的解决方案是:
public static void WriteElementString(this XmlWriter writer,
string localName,
string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
writer.WriteStartElement(localName);
writer.WriteString(value);
writer.WriteEndElement();
}
}
答案很接近,但正确的解决方案是:
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);
}
}
}