Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When i tried to pass a string as an xml document using string writer i am geting invalid xml string.

what i expected is
<?xml version="1.0" encoding="utf-8" standalone="yes"?><data><child>myvalue</child></data>


But I am getting
<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?><data><child>myvalue</child></data>


There is "\" charecter and its encoded as utf-16

What I have tried:

protected string BuildFindXmlSTR(string AgentName)
{
XmlWriterSettings setting = new XmlWriterSettings();
setting.Encoding = Encoding.UTF8;
string test = string.Empty;


StringBuilder sb = new StringBuilder();

using (StringWriter writer = new StringWriter(sb))
using (XmlWriter w = XmlWriter.Create(writer, setting))
{


w.WriteStartDocument(true);
w.WriteStartElement("data");

w.WriteElementString("child", "myvalue");

w.WriteEndElement();//data


}

test = sb.ToString();
return test;

}
Posted
Updated 30-Dec-19 10:00am
Comments

1 solution

StringWriter is going to force a UTF16 encoding, overwriting the XMLWriter utf8 setting. You'll need to tell SW that you only want a UTF8 encode. Again, take a look at Jon Skeet's answer here about subclassing the StringWriter's UTF encoding.
c# - XmlWriter to Write to a String Instead of to a File - Stack Overflow[^]

Edit: Quick and dirty mashup of Jon's example and your code. Does return utf-8.
C#
public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding
    {
        get { return Encoding.UTF8; }
    }
}

protected static string BuildFindXmlSTR(string AgentName)
{
    string test = string.Empty;

    using (TextWriter writer = new Utf8StringWriter())
    {
        using (XmlWriter w = XmlWriter.Create(writer))
        {
            w.WriteStartDocument(true);
            w.WriteStartElement("data");

            w.WriteElementString("child", "myvalue");

            w.WriteEndElement();//data
        }
        return writer.ToString();
    }
}
 
Share this answer
 
v3
Comments
[no name] 30-Dec-19 16:03pm    
+5 looks fine
[Edit]
Not sure what happens here. Two same questions answered with two nearly same answers. I will watch this....
Kris Lantz 31-Dec-19 7:55am    
It's odd that the question is near identical to the first time, but maybe the solution I offered previously wasn't enough. I figured mentioning Jon's answer specifically, and trying to show it does (I think) what the OP is looking for, was the best option here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900