views:

511

answers:

3

Here is how I'm currently converting XMLDocument to String

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

xmlDoc.WriteTo(xmlTextWriter);

return stringWriter.ToString();

The problem with this method is that if I have " ((quotes) which I have in attributes) it escapes them.

For Instance:

<Campaign name="ABC">
</Campaign>

Above is the expected XML. But it returns

<Campaign name=\"ABC\">
</Campaign>

I can do String.Replace "\" but is that method okay? Are there any side-effects? Will it work fine if the XML itself contains a "\"

+3  A: 

There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    xmlDoc.WriteTo(xmlTextWriter);
    return stringWriter.GetStringBuilder().ToString();
}
Darin Dimitrov
Did a MessageBox.Show() and you were correct :)
hab
+1 for fixing the code to use `using` blocks and not `XmlTextWriter`.
John Saunders
+5  A: 

Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?

retutn xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml... http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.outerxml(VS.71).aspx

mouters
Well you are right. I tried that first but when I saw the quotes in the debugger. I thought its because of OuterXml and try that StringWriter method. But I was wrong the quotes were only in the debugger. So I'll just use OuterXml. Thanks
hab
+1  A: 

" is shown \" in the debuger, but there is correct data in the string, and you don't need to replace anything, try to dump your string to the fail and you will note that the string is correct

ArsenMkrt