I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there\'s a pub
string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
Output:
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
The Xml Declaration isn't output by ToString(), but it is by Save() ...
XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
Output:
<?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
It sounds like you want to load the XML into an XmlTextWriter objects and set the Formatting and Indentation properties:
writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
If you just need to escape XML characters the following might be useful:
string myText = "This & that > <> <";
myText = System.Security.SecurityElement.Escape(myText);
Using the new System.Xml.Linq namespace (System.Xml.Linq Assembly) you can use the following:
string theString = "<nodeName>blah</nodeName>";
XDocument doc = XDocument.Parse(theString);
You can also create a fragment with:
string theString = "<nodeName>blah</nodeName>";
XElement element = XElement.Parse(theString);
If the string is not yet XML, you can do something like this:
string theString = "blah";
//creates <nodeName>blah</nodeName>
XElement element = new XElement(XName.Get("nodeName"), theString);
Something to note in this last example is that XElement will XML Encode the provided string.
I highly recommend the new XLINQ classes. They are lighter weight, and easier to user that most of the existing XmlDocument-related types.