1

I want to create an xml document and save it in string object.

I have refer both these question on SO for saving and encoding purpose

My code :

StringBuilder builder = new StringBuilder();

XDocument doc = new XDocument(new XElement("BANKID",
       new XElement("ReqID", "WEB"),
       new XElement("ReqHeader", "CASHDEP"),
       new XElement("CurrencyCode", ""),
       new XElement("CurrencyAbbrivation", "")));

using (TextWriter writer = new Utf8StringWriter(builder)) // Error Line
{
doc.Save(writer);
}
builder.ToString();

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }        
}

It gives me error saying "Utf8StringWriter does not contain a constructor that takes 1 arguments"

How to modify that class which would accept arguments as StringBuilder ?

Community
  • 1
  • 1
Shaggy
  • 5,422
  • 28
  • 98
  • 163
  • Similar to: [stackoverflow Q](http://stackoverflow.com/questions/3871738/force-xdocument-to-write-to-string-with-utf-8-encoding)? – Aidanapword May 06 '14 at 08:45

1 Answers1

2

Your custom Utf8StringWriter class has no constructor accepting a parameter, but you're trying to pass a value to it. That's why you're getting the error message.

Add a public constructor that accepts a StringBuilder, then pass it on to the base class:

public class Utf8StringWriter : StringWriter
{
    public Utf8StringWriter(StringBuilder stringBuilder)
        :base(stringBuilder)
    {
    }

    public override Encoding Encoding { get { return Encoding.UTF8; } }
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165