Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 "\"
Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?
return xmlDoc.OuterXml;
The OuterXml property returns a string version of the xml.
–
–
–
–
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);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
–
–
–
public static string AsString(this XmlDocument xmlDoc)
using (StringWriter sw = new StringWriter())
using (XmlTextWriter tx = new XmlTextWriter(sw))
xmlDoc.WriteTo(tx);
string strXmlText = sw.ToString();
return strXmlText;
Now to use simply:
yourXmlDoc.AsString()
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.